WPF BitmapImage Serialization / Deserialization

I am trying to Serialize and Deserialize BitmapImages. I use methods that supposedly work that I found in this thread: error in my byte [] to convert to WPF BitmapImage?

To repeat what happens, here is part of my Serialization code:

using (MemoryStream ms = new MemoryStream())
                {
                    // This is a BitmapImage fetched from a dictionary.
                    BitmapImage image = kvp.Value; 

                    PngBitmapEncoder encoder = new PngBitmapEncoder();
                    encoder.Frames.Add(BitmapFrame.Create(image));
                    encoder.Save(ms);

                    byte[] buffer = ms.GetBuffer();

                    // Here I'm adding the byte[] array to SerializationInfo
                    info.AddValue((int)kvp.Key + "", buffer);
                }

And here is the deserialization code:

// While iterating over SerializationInfo in the deserialization
// constructor I pull the byte[] array out of an 
// SerializationEntry
using (MemoryStream ms = new MemoryStream(entry.Value as byte[]))
                    {
                        ms.Position = 0;

                        BitmapImage image = new BitmapImage();
                        image.BeginInit();
                        image.StreamSource = ms;
                        image.EndInit();

                        // Adding the timeframe-key and image back into the dictionary
                        CapturedTrades.Add(timeframe, image);
                    }

Also, I'm not sure if that matters, but earlier, when I populated my dictionary, I encoded Bitmaps using PngBitmapEncoder to get them in BitmapImages. Therefore, I am not sure that double coding has anything to do with it. Here is the method that does this:

// Just to clarify this is done before the BitmapImages are added to the
// dictionary that they are stored in above.
private BitmapImage BitmapConverter(Bitmap image)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                BitmapImage bImg = new BitmapImage();
                bImg.BeginInit();
                bImg.StreamSource = new MemoryStream(ms.ToArray());
                bImg.EndInit();
                ms.Close();

                return bImg;
            }
        }

, , . , , BitmapImages, / "0", . , , , .

, - , ?

!

+3
1

1) MemoryStream, . using

using (MemoryStream ms = new MemoryStream(entry.Value as byte[]))

2)

encoder.Save(ms);

ms.Seek(SeekOrigin.Begin, 0);
ms.ToArray();
+6

Source: https://habr.com/ru/post/1777555/


All Articles