从varbinary case sql server读取映像c#

时间:2014-06-05 08:46:07

标签: c# sql sql-server image

我尝试将流转换为图片时遇到问题。它显示了一个错误: Image returnImage = Image.FromStream(ms);

if (reader[12] != System.DBNull.Value)
{
    Byte[] image = (Byte[])reader[12];
    c.image = byteArrayToImage(image);
}

public Image byteArrayToImage(byte[] byteArrayIn)
{
    MemoryStream ms = new MemoryStream();
    ms.Write(byteArrayIn, 0, byteArrayIn.Length);
    ms.Seek(0, SeekOrigin.Begin);
    ms.Close();
    Image returnImage = Image.FromStream(ms);
    return returnImage;
}

2 个答案:

答案 0 :(得分:3)

你不应该关闭

   ms.Close();  // <- That's wrong:
   // You can't create an image from a disposed stream
   Image returnImage = Image.FromStream(ms); 

这样做:

  ...
  using (MemoryStream ms = new MemoryStream()) {
    ms.Write(byteArrayIn, 0, byteArrayIn.Length);
    ms.Seek(0, SeekOrigin.Begin);

    return Image.FromStream(ms);
  }

答案 1 :(得分:3)

MemoryStream ms = new MemoryStream();
ms.Write(byteArrayIn, 0, byteArrayIn.Length);
ms.Seek(0, SeekOrigin.Begin);
ms.Close();  // <-- Remove this line

Image returnImage = Image.FromStream(ms);
return returnImage;

在此代码中,您在创建图像之前关闭流。您无法从封闭的流中读取。将您的代码更改为:

using (MemoryStream ms = new MemoryStream(byteArrayIn))
{
    Image returnImage = Image.FromStream(ms);
    return returnImage;
}

该代码可能生成GDI +错误。因此,您根本不必担心不会丢弃流。垃圾收集器无论如何都会这样做,所以如果你在GDI +中遇到错误,请使用:

MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
return returnImage;