2010-11-29 27 views
3

私はBitmapImageをシリアル化および逆シリアル化しようとしていました。私は、このスレッドで見つけおそらく働く方法を使用してきた:error in my byte[] to WPF BitmapImage conversion?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); 
        } 

はまた、私はわからないが、私は私の辞書を埋めたときに、以前の私はBitmapImagesにそれらを取得するためにPngBitmapEncoderでビットマップをエンコードされました。ダブルエンコーディングと何か関係があるかどうかは分かりません。以下のような方法があります。

// 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」に設定されます。もちろん、画像を表示しようとすると何も表示されません。

なぜ、それらが正しく非直列化されていないのかについての考えはありますか?

ありがとうございます!

答えて

6

1)イメージの初期化で使用されたMemoryStreamを破棄しないでください。あなたは覚えていれば私が見る今日の私を助けるために再び

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

を追加

encoder.Save(ms); 

てみた後、このライン

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

2)でusingを削除し、あなたはDeflateStreamsのyeseterdayで私を助けました。あなたの変更を適用し、今それは完全に動作します、もう一度ありがとう! – vesz

+0

運勢)同じようなことをしているようです。 –

+0

これについていくつかの説明があります。開始しようとした後、ms.GetBuffer()をms.GetArray()に変更するソリューションはありましたか? –

関連する問題