2015-06-29 80 views
0

嗨我正在圖像存儲在SQL服務器。數據類型是Image。System.ArgumentException:參數無效。在C#

,同時從我得到錯誤像

System.ArgumentException數據庫中檢索圖片:參數無效。

錯誤發生在這一行img = Image.FromStream(ms)

private void RetriveImage_Click(object sender, EventArgs e)  
{  
    SqlConnection con = new SqlConnection(constr);   
    con.Open(); 
    Image img; 

    try 
    { 
     cmd = new SqlCommand("select Pic from emguimg where ID =" + cbxID.SelectedItem, con); 

     SqlDataReader dr = cmd.ExecuteReader(); 

     DataTable dt = new DataTable(); 
     dt.Load(dr); 

     byte[] bytes = (byte[])dt.Rows[0]["Pic"]; 

     MemoryStream ms = new MemoryStream(bytes); 
     ms.Write(bytes, 0, bytes.Length); 

     img = Image.FromStream(ms); 


     PicBox.Image = img; 
     PicBox.SizeMode = PictureBoxSizeMode.StretchImage; 
     PicBox.BorderStyle = BorderStyle.Fixed3D; 

     ms.Flush(); 
     ms.Close(); 
    } 
    catch (Exception ex) 
    { 
     WriteLogMessage(ex.ToString()); 
    } 
} 
+0

'(byte [])((byte [])dt.Rows [0] [「Pic」])'是否真的有必要?你有沒有檢查你有有效的字節代表一個已知的圖像格式? – leppie

+0

我不認爲sql datatype'Image'與.NET圖像兼容。最好使用本地字節來將圖像存儲在數據庫中。 –

+0

您的流爲空或者流中的字節不代表有效圖像。 –

回答

0

填充後的MemoryStream尋求從此流加載圖像之前定位0

ms.Write(bytes, 0, bytes.Length); 
ms.Position = 0; //insert this line 
img = Image.FromStream(ms);