WPF BitmapImage序列化/反序列化

4
我一直在尝试对BitmapImages进行序列化和反序列化。我使用的是这个线程中所找到的据称有效的方法:error in my byte[] to WPF BitmapImage conversion? 为了重申正在发生的事情,这是我的序列化代码的一部分:
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);
                }

以下是反序列化代码:

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

此外,我不确定这是否重要,但早些时候在填充字典时,我使用PngBitmapEncoder对位图进行编码,以将它们转换为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;
            }
        }

问题是,序列化和反序列化都正常工作。没有错误,并且字典中有条目似乎是BitmapImages,但当我在调试模式下查看它们时,它们的宽度/高度和某些其他属性都设置为“0”。当然,当我尝试显示图像时,什么也没有显示。

那么,你有什么想法为什么它们没有被正确反序列化吗?

谢谢!

1个回答

7

1) 在图像初始化过程中使用的MemoryStream不应该被丢弃,因此请删除此行中的using代码。

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

2) 在之后

encoder.Save(ms);

尝试添加

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

今天又回来帮我了,如果你还记得,昨天你帮我解决了DeflateStreams的问题。我应用了你的更改,现在它完美地工作了,再次感谢! - hillsprig
看来我们做着相似的事情。 - The Smallest
寻求一些澄清。在将指针定位到开头后,解决方案是将ms.GetBuffer()更改为ms.GetArray()吗? - SomeInternetGuy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接