2014-02-22 151 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上的答案可以帮助你解决一些问题。