2013-04-10 36 views
3

當我嘗試使用BinaryFormatter序列化一些圖像時,我將得到一個ExternalException - 在GDI +中發生的一般錯誤。一段時間,我決定創建一個簡單的測試項目,以縮小問題:BinaryFormatter.Serialize(Image) - ExternalException - 在GDI中發生了一般性錯誤+

static void Main(string[] args) 
    { 
     string file = @"C:\temp\delme.jpg"; 

     //Image i = new Bitmap(file); 
     //using(FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read)) 

     byte[] data = File.ReadAllBytes(file); 
     using(MemoryStream originalms = new MemoryStream(data)) 
     { 
      using (Image i = Image.FromStream(originalms)) 
      { 
       BinaryFormatter bf = new BinaryFormatter(); 

       using (MemoryStream ms = new MemoryStream()) 
       { 
        // Throws ExternalException on Windows 7, not Windows XP 
        bf.Serialize(ms, i); 
       } 
      } 
     } 
    } 

對於具體的圖像,我已經試過各種加載圖像的方式,我無法得到它的工作在Windows下7,運行程序作爲管理員。

即使我已經複製了確切的SAM e可執行文件和映像到我的Windows XP VMWare實例中,並且我沒有任何問題。

任何人都有的,爲什麼一些圖像不會在Windows 7下運行的任何想法,但XP下工作?


這裏的圖像之一: http://www.2shared.com/file/7wAXL88i/SO_testimage.html

delme.jpg MD5:3d7e832db108de35400edc28142a8281

+0

請提供有問題的圖像之一(上傳某處並給我們鏈接)。 – 2013-04-10 04:00:15

+0

你好,請你選擇最能滿足你需求的帖子作爲答案嗎? – 2013-04-16 02:10:15

回答

3

由於OP指出,所提供的代碼拋出,這似乎是與他所提供的圖像僅發生,但正常工作與我的機器上的其他圖像異常。

選項1

static void Main(string[] args) 
{ 
    string file = @"C:\Users\Public\Pictures\delme.jpg"; 

    byte[] data = File.ReadAllBytes(file); 
    using (MemoryStream originalms = new MemoryStream(data)) 
    { 
     using (Image i = Image.FromStream(originalms)) 
     { 
      BinaryFormatter bf = new BinaryFormatter(); 

      using (MemoryStream ms = new MemoryStream()) 
      { 
       // Throws ExternalException on Windows 7, not Windows XP       
       //bf.Serialize(ms, i); 

       i.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp); // Works 
       i.Save(ms, System.Drawing.Imaging.ImageFormat.Png); // Works 
       i.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); // Fails 
      }  
     } 
    } 
} 

這可能是有問題的圖像與補充說,與JPEG系列化干擾一些額外的信息的工具創建的。

P.S.圖像可以被保存到使用BMPPNG格式存儲器流。如果更改格式是一個選項,那麼您可以嘗試使用這些格式或ImageFormat中定義的任何其他格式。

選項2 如果你的目標只是爲了獲得的圖像文件的內容到一個內存流,然後做只是下面將有助於

static void Main(string[] args) 
{ 
    string file = @"C:\Users\Public\Pictures\delme.jpg"; 
    using (FileStream fileStream = File.OpenRead(file)) 
    { 
     MemoryStream memStream = new MemoryStream(); 
     memStream.SetLength(fileStream.Length); 
     fileStream.Read(memStream.GetBuffer(), 0, (int)fileStream.Length); 
    } 
} 
+0

只是想補充說,另一個解決方案是創建一個圖像的副本和序列化,但由於這是不可接受的(因爲一些圖像可能會非常大),我最終重寫代碼和其他方法來完全刪除序列化。只需在Win7上運行項目而不是WinXP就可以完成很多工作。 :[ – 2013-04-17 17:26:26

2

雖然Bitmap類被標記爲[Serializable],實際上它並不支持序列化。您可以做的最好做法是將包含原始圖像數據的byte[]序列化,然後使用MemoryStreamImage.FromStream()方法重新創建它。

我無法解釋您遇到的不一致的行爲;對我來說,它無條件失敗(儘管我在嘗試在不同的應用程序域之間封送圖像時首先發現了這一點,而不是手動將它們序列化)。

相關問題