4

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

そして、ここに逆シリアル化コードがあります:

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

また、それが問題かどうかはわかりませんが、以前に辞書にデータを入力したときに、Bitmaps を 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」に設定されています。もちろん、画像を表示しようとしても何も表示されません。

なぜそれらが適切に逆シリアル化されないのかについてのアイデアはありますか?

ありがとう!

4

1 に答える 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();
于 2010-11-29T22:41:51.323 に答える