我一直在尝试序列化和绝对化的位图像。我一直在使用据说可以在此线程中发现的方法: 我的字节[]错误到WPF位映射转换?

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

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编码了bitmap,以使它们进入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;
            }
        }

因此,问题是,序列化和避免效果很好。没有错误,字典的条目似乎是位图像,但是当我在调试模式中查看它们时,它们的宽度/高度和其他某些属性都设置为“ 0”。当然,当我尝试显示图像时,什么都没有显示。

那么,为什么他们没有正确地进行挑选?

谢谢!

有帮助吗?

解决方案

1)您不应处理图像初始化中使用的内存流。消除 using 在这条线中

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

2)之后

encoder.Save(ms);

尝试添加

ms.Seek(SeekOrigin.Begin, 0);
ms.ToArray();
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top