Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
523 views
in Technique[技术] by (71.8m points)

c# - Convert RenderTargetBitmap to BitmapImage

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 ?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...