2014-02-22 154 views
-2

我在將圖像轉換爲SQL Server中的字節後存儲圖像,但出現了問題,即無法將字節轉換爲字節[]。 這裏是代碼,請發送您寶貴的回覆。字節到字節[]轉換?

protected void btnSubmit_Click(object sender, EventArgs e) 
{ 
    if (fpPhoto.HasFile) 
    { 
     if (fpPhoto.PostedFile.ContentType == "image/jpg" || 
      fpPhoto.PostedFile.ContentType == "image/jpeg" || 
      fpPhoto.PostedFile.ContentType == "image/png") 
     { 
      byte[] imagebytes = new byte[fpPhoto.PostedFile.ContentLength]; 
      int filelenght = fpPhoto.PostedFile.ContentLength; 
      imagebytes = fpPhoto.FileBytes; 
      fpPhoto.PostedFile.InputStream.Read(imagebytes, 0, filelenght); 
     } 
    } 

    User objUser = new User(); 

    objUser.UserName_Pk = txtUserName.Text; 
    objUser.Password = txtPassword.Text; 
    objUser.MobileNo = txtMobileNo.Text; 
    objUser.Email = txtEmail.Text; 
    objUser.SecurityAnswer = txtAnswer.Text; 
    objUser.Photo = Convert.ToByte(imagebytes); // Here Error occurs 

    objUserBll.InsertUpdate(objUser); 
} 
+0

哪條線你有錯誤? –

+1

什麼數據類型是'objUser.Photo'? – LGSon

+0

Photo的數據類型是什麼? –

回答

0

試試這個

如果照片數據類型是byte[]

objUser.Photo= BitConverter.GetBytes(imagebytes); 
+0

如果它們是'byte []'他爲什麼需要這樣做? ... imagebytes已經是'byte []' – LGSon

+1

Tnaks它的工作.. :) –

+0

如果它的工作,那麼請接受我的答案。這對其他人有幫助 –

0

由於imagebytes應該已經是一個字節數組(byte[]),您無需將其轉換。只是刪除Convert.ToByte(),你是好去:

objUser.Photo = imagebytes; 

如果Photo不是字節數組呢,我建議你改變它的數據類型byte[],你顯然希望保存的照片,這通常意味着存儲二進制數據。

另外,請查看if塊中變量名爲imagebytes的聲明。爲了在最後使用變量進行賦值,您需要將該聲明移到if塊之外,以便之前聲明該變量。下面的代碼應該足夠(以目前的形式,爲您打造您在指定FileBytes它覆蓋隨即一個新的數組):

// Declare variable outside of first if block 
byte[] imagebytes; 
if (fpPhoto.HasFile) 
{ 
    // ... 

BTW:我剛回答了一個非常類似的問題與幾乎相同的一段代碼here。也許你會發現有用的東西。由於代碼幾乎完全相同,問題在同一時間段內提出,所以我懷疑這是作業。在這種情況下,儘自己的利益,並確保你真正理解任務和他們的解決方案,即使在SO上的答案可以幫助你解決一些問題。