0

可能重复:
GDI+ 一般错误

我正在编写一个数据库应用程序并使用“sdf”文件作为数据库。我通过以下代码将图像转换为字节数组,将图像保存在数据库中:

byte[] ReadFile(string sPath)
    {

        //Initialize byte array with a null value initially.
        byte[] data = null;

        //Use FileInfo object to get file size.
        FileInfo fInfo = new FileInfo(sPath);
        long numBytes = fInfo.Length;

        //Open FileStream to read file
        FileStream fStream = new FileStream(sPath, FileMode.Open, FileAccess.Read);

        //Use BinaryReader to read file stream into byte array.
        BinaryReader br = new BinaryReader(fStream);

        //When you use BinaryReader, you need to supply number of bytes to read from file.
        //In this case we want to read entire file. So supplying total number of bytes.
        data = br.ReadBytes((int)numBytes);
        return data;
    }

并将其插入数据库。

我通过此代码检索图像:

public static Image CreateImage(byte[] imageData)
    {
        Image image=null;
        if(imageData !=null)
        {
            using (MemoryStream inStream = new MemoryStream())
            {
                  inStream.Write(imageData, 0, imageData.Length);

                  image = Bitmap.FromStream(inStream);
            }
        }


        return image;
    }

并将图片框图像分配给 CreateImage 返回值。

直到这里一切都很好但是当我想在磁盘上存储图片框图像时

 Bpicture.Image.Save(@"pic1.jpeg", ImageFormat.Jpeg);

发生此错误:

An unhandled exception of type 'System.Runtime.InteropServices.ExternalException' occurred in System.Drawing.dll

Additional information: A generic error occurred in GDI+.

当我从磁盘而不是数据库加载图像时,也不会发生此错误

4

1 回答 1

0

尝试修改您的代码:

inStream.Write(imageData, 0, imageData.Length);
inStream.Seek(0, SeekOrigin.Begin);
image = Bitmap.FromStream(inStream);

stream 是一个特定的结构,它有一个需要移动到开头的指针才能读取刚刚写入它的数组。

于 2012-11-27T13:45:34.923 回答