c#将base64转换为jpg图像

时间:2016-11-15 03:38:28

标签: c#

  protected void ExportToImage(object sender, EventArgs e)
    {
        string base64 = Request.Form[hfImageData.UniqueID].Split(',')[1];
        byte[] bytes = Convert.FromBase64String(base64);
        File.Copy(bytes.ToString()+".jpg", "\\\\192.168.2.9\\Web");
    }

我从jquery获得的hfImageData数据,在用户完成绘图之后,我将 convas 转换为base64。 然后调用c#函数将base64转换为jpg图像文件到服务器并存储到DB中。

当我触发onclick按钮时出现错误: System.IO.FileNotFoundException:找不到文件'System.Byte []。jpg'。

任何想法为什么?

2 个答案:

答案 0 :(得分:2)

bytes.ToString()不会返回任何有意义的内容。

你的字节不是文件;你无法复制它们。

相反,请调用File.WriteAllBytes()将它们直接写入新文件。

答案 1 :(得分:0)

在这一行File.Copy(bytes.ToString()+".jpg", "\\\\192.168.2.9\\Web");中,您实际上是在尝试转换bytes数组的内容并将其用作图像名称,但这实际上并不会创建该文件。

bytes.ToString()只返回对象的类型而不是内容。这就是你看到System.Byte[].jpg

的原因

解决问题的方法是改变你的功能:

protected void ExportToImage(object sender, EventArgs e)
{
    string base64 = Request.Form[hfImageData.UniqueID].Split(',')[1];
    byte[] bytes = Convert.FromBase64String(base64);
    //write the bytes to file:
    File.WriteAllBytes(@"c:\temp\somefile.jpg", bytes); //write to a temp location.
    File.Copy(@"c:\temp\somefile.jpg", @"\\192.168.2.9\Web");//here we grab the file and copy it.
    //EDIT: based on permissions you might be able to write directly to the share instead of a temp folder first.
}
相关问题