12

我有一个RenderTargetBitmap,我需要将其转换为BitmapImage. 请检查下面的代码。

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

在上面的代码中,我使用了 Image。现在我需要使用 BitmapImage。我怎样才能做到这一点?

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

2 回答 2

22

尽管似乎没有必要将 a 转换RenderTargetBitmap为 a BitmapImage,但您可以轻松地将 a 编码RenderTargetBitmap为 a并从该流中MemoryStream解码 the 。BitmapImage

WPF中有几个BitmapEncoder,下面的示例代码使用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();
}
于 2012-12-21T10:59:34.300 回答
-1
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);
}

这看起来是一个更简单的解决方案。

于 2016-09-10T22:42:56.220 回答