2011-09-14 54 views
15

使用C#,我試圖從磁盤加載JPEG文件並將其轉換爲字節數組。到目前爲止,我有這樣的代碼:將JPEG圖像轉換爲字節數組 - COM異常

static void Main(string[] args) 
{ 
    System.Windows.Media.Imaging.BitmapFrame bitmapFrame; 

    using (var fs = new System.IO.FileStream(@"C:\Lenna.jpg", FileMode.Open)) 
    { 
     bitmapFrame = BitmapFrame.Create(fs); 
    } 

    System.Windows.Media.Imaging.BitmapEncoder encoder = 
     new System.Windows.Media.Imaging.JpegBitmapEncoder(); 
    encoder.Frames.Add(bitmapFrame); 

    byte[] myBytes; 
    using (var memoryStream = new System.IO.MemoryStream()) 
    { 
     encoder.Save(memoryStream); // Line ARGH 

     // mission accomplished if myBytes is populated 
     myBytes = memoryStream.ToArray(); 
    } 
} 

但是,在執行行ARGH給我的留言:

收到COMException了未處理。句柄無效。 (異常來自HRESULT :0x80070006(E_HANDLE))

我不覺得有什麼特別之處文件Lenna.jpg - 我下載了它從http://computervision.wikia.com/wiki/File:Lenna.jpg。你能告訴上面的代碼有什麼問題嗎?

回答

36

檢查從本文的例子:http://www.codeproject.com/KB/recipes/ImageConverter.aspx

而且最好是使用類從System.Drawing

Image img = Image.FromFile(@"C:\Lenna.jpg"); 
byte[] arr; 
using (MemoryStream ms = new MemoryStream()) 
{ 
    img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); 
    arr = ms.ToArray(); 
} 
3

這種錯誤發生的原因是因爲您正在使用默認爲BitmapFrame.Create()方法按需加載。在調用encoder.Save之前,BitmapFrame不會嘗試讀取它所關聯的流,流的哪一點已經處理完畢。

你可以任一包裹整個函數在使用{}塊,或使用替代BitmapFrame.Create(),如:

BitmapFrame.Create(fs, BitmapCreateOptions.None, BitmapCacheOption.OnLoad); 
4
public byte[] imageToByteArray(System.Drawing.Image imageIn) 
{ 
MemoryStream ms = new MemoryStream();  

imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif); 
return ms.ToArray(); 
} 
7

其他建議:

byte[] image = System.IO.File.ReadAllBytes (Server.MapPath ("noimage.png")); 

應該不僅與圖像工作。

相關問題