WPF BitmapImage序列化/反序列化

ves*_*esz 3 wpf serialization bitmapimage deserialization

我一直在尝试序列化和反序列化BitmapImages.我一直在使用我认为在这个线程中找到的方法:我的byte []错误到WPF BitmapImage转换?

只是为了迭代正在发生的事情,这是我的序列化代码的一部分:

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);
                }
Run Code Online (Sandbox Code Playgroud)

这是反序列化代码:

// 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);
                    }
Run Code Online (Sandbox Code Playgroud)

此外,我不确定它是否重要,但早些时候,当我填充我的字典时,我使用PngBitmapEncoder对Bitmaps进行编码,以使它们进入BitmapImages.所以不确定双重编码是否与它有关.这是执行此操作的方法:

// 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;
            }
        }
Run Code Online (Sandbox Code Playgroud)

所以问题是,序列化和反序列化工作正常.没有错误,字典中的条目似乎是BitmapImages,但是当我在调试模式下查看它们时,它们的宽度/高度和其他一些属性都被设置为'0'.当然,当我尝试显示图像时,没有显示任何内容.

那么关于为什么它们没有被正确反序列化的任何想法?

谢谢!

The*_*est 6

1)您不应该处置从图像初始化使用的MemoryStream.删除using此行

using (MemoryStream ms = new MemoryStream(entry.Value as byte[]))
Run Code Online (Sandbox Code Playgroud)

2)之后

encoder.Save(ms);
Run Code Online (Sandbox Code Playgroud)

尝试添加

ms.Seek(SeekOrigin.Begin, 0);
ms.ToArray();
Run Code Online (Sandbox Code Playgroud)