2009-05-31 83 views
1

我有一個將文件提取到字節數組(數據)的函數。C#位圖圖像,字節數組和流!

 int contentLength = postedFile.ContentLength; 
     byte[] data = new byte[contentLength]; 
     postedFile.InputStream.Read(data, 0, contentLength); 

後來我用這個字節數組構造一個爲System.Drawing.Image對象 (其中數據是字節數組)

 MemoryStream ms = new MemoryStream(data); 
     Image bitmap = Image.FromStream(ms); 

我得到下面的異常「的ArgumentException:參數無效「。

的原貼文件包含一個500K JPEG圖像...

任何想法,爲什麼這個心不是工作?

注意:我向你保證轉換爲字節數組然後轉換爲內存數據流的有效理由!

+0

數據是否包含圖像數據?你不會說'postedFile`是什麼類型。 – ChrisF 2009-05-31 16:19:05

+1

你在哪裏得到這個錯誤?您發佈的代碼應該可以正常工作... – 2009-05-31 16:19:19

+0

postedFile是一個HttpPostedFileBase。 錯誤發生在圖像上bitmap = Image.FromStream(ms); :( – iasksillyquestions 2009-05-31 16:22:31

回答

5

這很可能是因爲您沒有將所有文件數據都存入字節數組中。 Read方法不需要返回你請求的字節數,而是返回實際放入數組中的字節數。您必須循環,直到獲得所有數據:

int contentLength = postedFile.ContentLength; 
byte[] data = new byte[contentLength]; 
for (int pos = 0; pos < contentLength;) { 
    pos += postedFile.InputStream.Read(data, pos, contentLength - pos); 
} 

從流中讀取時這是一個常見的錯誤。我已經看到這個問題很多次了。

編輯:
隨着支票流的早日結束,馬修建議,代碼爲:

int contentLength = postedFile.ContentLength; 
byte[] data = new byte[contentLength]; 
for (int pos = 0; pos < contentLength;) { 
    int len = postedFile.InputStream.Read(data, pos, contentLength - pos); 
    if (len == 0) { 
     throw new ApplicationException("Upload aborted."); 
    } 
    pos += len; 
} 
1

你不檢查postedFile.InputStream的返回值。 Read。這是而不是保證在第一次通話時填滿陣列。這會在數據中留下損壞的JPEG(0代替文件內容)。

0

我在使用更強大的圖像庫可打開的.NET中加載圖像時遇到了問題。 .NET可能不支持您所具有的特定jpeg圖像。 jpeg文件不僅僅是一種編碼類型,還有許多可能的壓縮方案。

您可以使用其他支持格式的圖片進行試用。

1

您是否檢查過Read()調用的返回值以驗證是否實際讀取了所有內容?也許Read()只返回流的一部分,要求你循環Read()調用,直到所有的字節被消耗完。

1

任何理由,你爲什麼不只是這樣做:

Image bitmap = Image.FromStream(postedFile.InputStream);