Convert RenderTargetBitmap to BitmapImage

后端 未结 2 1860
南方客
南方客 2020-12-09 12:08

I have a RenderTargetBitmap, I need to convert it to BitmapImage. Please check the code below.

 RenderTargetBitmap bitMap = getRend         


        
相关标签:
2条回答
  • 2020-12-09 12:40
    private async void Button_Click(object sender, RoutedEventArgs e)
    {
        RenderTargetBitmap bitMap = new RenderTargetBitmap();
        await bitMap.RenderAsync(grid);
        Image image = new Image();// This is a Image
        image.Source = bitMap;
        image.Height = 150;
        image.Width = 100;
    
        grid.Children.Add(image);
    }
    

    This looks as a simpler solution.

    0 讨论(0)
  • 2020-12-09 12:50

    Although it doesn't seem to be necessary to convert a RenderTargetBitmap into a BitmapImage, you could easily encode the RenderTargetBitmap into a MemoryStream and decode the BitmapImage from that stream.

    There are several BitmapEncoders in WPF, the sample code below uses a PngBitmapEncoder.

    var renderTargetBitmap = getRenderTargetBitmap();
    var bitmapImage = new BitmapImage();
    var bitmapEncoder = new PngBitmapEncoder();
    bitmapEncoder.Frames.Add(BitmapFrame.Create(renderTargetBitmap));
    
    using (var stream = new MemoryStream())
    {
        bitmapEncoder.Save(stream);
        stream.Seek(0, SeekOrigin.Begin);
    
        bitmapImage.BeginInit();
        bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
        bitmapImage.StreamSource = stream;
        bitmapImage.EndInit();
    }
    
    0 讨论(0)
提交回复
热议问题