Convert RenderTargetBitmap to BitmapImage

荒凉一梦 提交于 2019-12-17 18:41:12

问题


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

 RenderTargetBitmap bitMap = getRenderTargetBitmap();
 Image image = new Image();// This is a Image
 image.Source = bitMap;

In the above code I have used Image.Now I need to use a BitmapImage. How can I do this?

 RenderTargetBitmap bitMap = getRenderTargetBitmap();
 BitmapImage image = new BitmapImage();// This is a BitmapImage
 // how to set bitMap as source of BitmapImage ?

回答1:


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();
}



回答2:


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.



来源:https://stackoverflow.com/questions/13987408/convert-rendertargetbitmap-to-bitmapimage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!