C# 将 RenderTargetBitmap 转换为 BitmapImage
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13987408/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert RenderTargetBitmap to BitmapImage
提问by sharmila
I have a RenderTargetBitmap
, I need to convert it to BitmapImage
. Please check the code below.
我有一个RenderTargetBitmap
,我需要将其转换为BitmapImage
. 请检查下面的代码。
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?
在上面的代码中,我使用了 Image.Now 我需要使用 BitmapImage。我怎样才能做到这一点?
RenderTargetBitmap bitMap = getRenderTargetBitmap();
BitmapImage image = new BitmapImage();// This is a BitmapImage
// how to set bitMap as source of BitmapImage ?
采纳答案by Clemens
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.
尽管似乎没有必要将 a 转换RenderTargetBitmap
为 a BitmapImage
,但您可以轻松地将 a编码RenderTargetBitmap
为 aMemoryStream
并BitmapImage
从该流中解码。
There are several BitmapEncodersin WPF, the sample code below uses a PngBitmapEncoder
.
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();
}
回答by Иван Гомонюк
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.
这看起来是一个更简单的解决方案。