GDI +中发生了一般错误。当试图在磁盘上保存图片框图像时

时间:2012-11-27 13:37:27

标签: c# .net gdi+

  

可能重复:
  GDI+ Generic Error

我正在编写数据库应用程序并使用“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;
    }

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

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

 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+.

当我从磁盘而不是数据库

加载图像时,也不会发生此错误

1 个答案:

答案 0 :(得分:0)

尝试修改您的代码:

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

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