【问题标题】:Image cannot be converter from byte array and display in picture box图像不能从字节数组转换并显示在图片框中
【发布时间】:2014-07-21 00:03:29
【问题描述】:

我正在使用 Visual Studio 2010 创建一个 Windows 应用程序。使用 SQL Server 2008 R2 作为数据库并将图像保存为数据类型 image。上传成功。但我在从数据库中检索图像并将其显示在 PictureBox 中时出现错误 Parameter invalid

这是我的代码

 byte[] pic = ((byte[])dr["image1"]);
    Image newImage;

    using (MemoryStream ms = new MemoryStream(pic, 0, Convert.ToInt32(pic.Length))) 
    {
        ms.Write(pic, 0, pic.Length);

        //Set image variable value using memory stream.
        newImage = Image.FromStream(ms, true);
    }

    //set picture
    pictureBox1.Image = newImage;

【问题讨论】:

  • image 数据类型将在 SQL Server 的未来版本中删除。避免在新的开发工作中使用此数据类型,并计划修改当前使用它们的应用程序。请改用varbinary(max)See details here

标签: visual-studio-2010 c#-4.0 sql-server-2008-r2


【解决方案1】:

很可能,图像没有正确保存到数据库中。您可以发布您正在使用的代码吗?

【讨论】:

  • if (pictureBox1.Image != null) { MemoryStream ms = new MemoryStream(); pictureBox1.Image.Save(ms, pictureBox1.Image.RawFormat);字节[] bimage = ms.GetBuffer(); ms.Close(); string ins = "插入注册(image1,path)值('" + bimage + "','" + t + "')"; obj.Exe_NonQuery(ins); MessageBox.Show("保存成功"); }
  • 我也试试这段代码 ** if (pictureBox1.Image != null) { ImageConverter converter = new ImageConverter(); byte[] bimage = (byte[])converter.ConvertTo(pictureBox1.Image, typeof(byte[])); string ins = "插入注册(image1,path)值('" + bimage + "','" + t + "')"; obj.Exe_NonQuery(ins); MessageBox.Show("保存成功"); }**
  • 需要使用参数来插入byte[]类型的值。另外,使用 ms.ToArray() 而不是 ms.GetBuffer()。
【解决方案2】:

您正在创建一个包含图像数据的内存流,但随后又将图像数据写入该流。只需创建内存流并使用它:

byte[] pic = (byte[])dr["image1"];
Image newImage;
using (MemoryStream ms = new MemoryStream(pic)) {
  //Set image variable value using memory stream.
  newImage = Image.FromStream(ms, true);
}
//set picture
pictureBox1.Image = newImage;

【讨论】:

    猜你喜欢
    • 2013-08-07
    • 2011-11-25
    • 2010-09-21
    • 2021-03-25
    • 1970-01-01
    • 2021-04-21
    • 1970-01-01
    • 1970-01-01
    • 2014-12-11
    相关资源
    最近更新 更多