Reputation: 129
I have a BitmapFrame from deserialization. I need to convert this to BitmapImage. How to do that? I used this code:
The problem is that BitmapImage does not have a Source property, only StreamSource or UriSource.
serialization part:
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
MemoryStream stream = new MemoryStream();
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(image.UriSource));
encoder.QualityLevel = 30;
encoder.Save(stream);
stream.Flush();
info.AddValue("Image", stream.ToArray());
...
deserialization :
public ImageInfo(SerializationInfo info, StreamingContext context)
{
//Deserialization Constructorbyte[] encodedimage = (byte[])info.GetValue("Image", typeof(byte[]));
if (encodedimage != null)
{
MemoryStream stream = new MemoryStream(encodedimage);
JpegBitmapDecoder decoder = new JpegBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.Default);
Image = new BitmapImage();
Image.BeginInit();
//Image.StreamSource = ... decoder.Frames[0];
Image.EndInit();
Image.Freeze();
}
...
I would need something effective instead of the comment above...
Upvotes: 1
Views: 1264
Reputation: 128116
Besides that you don't really need this conversion (because you can use a BitmapFrame wherever you otherwise use a BitmapImage), you could directly decode a BitmapImage from an encoded bitmap in a byte array.
It is not necessary to explicitly use a BitmapDecoder. When you assign a Stream to the BitmapImage's StreamSource
property, the frameworks uses the appropriate decoder automatically. You must take care to set BitmapCacheOption.OnLoad
when the Stream should be closed immediately after the BitmapImage was created.
Image = new BitmapImage();
using (var stream = new MemoryStream(encodedimage))
{
Image.BeginInit();
Image.CacheOption = BitmapCacheOption.OnLoad;
Image.StreamSource = stream;
Image.EndInit();
}
Image.Freeze();
Upvotes: 1