c#中使用ImageConverter从图像到字节数组的转换失败

本文关键字:数组 到字节 转换 失败 图像 ImageConverter | 更新日期: 2023-09-27 18:16:26

我正在将我的图像从picturebox转换为字节数组

   public static byte[] ImageToByte(Image img)
    {
        ImageConverter converter = new ImageConverter();
        return (byte[])converter.ConvertTo(img, typeof(byte[]));
    }

,然后将字节数组转换为图像

  public static Image byteArrayToImage(byte[] imageData)
    {
        try
        {
            Image image;
            using (MemoryStream inStream = new MemoryStream())
            {
                inStream.Write(imageData, 0, imageData.Length);
                image = Bitmap.FromStream(inStream);
            }
            return image;
        }
        catch { throw; }
    }

这里是我保存数据之前的第一次,我将文件从本地系统上传到图片框

       openFileDialog1.Filter = "JPG Files (*.jpg)|*.jpg|JPEG Files (*.jpeg)|*.jpeg";
        if (openFileDialog1.ShowDialog() != DialogResult.Cancel)
        {
            Image pic = Image.FromFile(openFileDialog1.FileName);
            pboxPhoto.Image = pic;
        }

它是100%的工作第一次我保存数据到数据库。当我检索数据时,我正在将数据从检索到的字节数组转换为Image并附加到picturebox。到现在为止一切都很好。现在我想更新所有记录,这次ImagetoByte arrat方法抛出了一个异常

A generic error occurred in GDI+.

所以我的问题是当我从本地系统上传图像转换时,但是当我将字节数组转换为图像然后尝试将图像转换为字节数组时,抛出上述异常的方法。谢谢你. .

c#中使用ImageConverter从图像到字节数组的转换失败

问题是,当您处置MemoryStream时,您关闭了byteArrayToImage中位图的底层流。

你不能对Bitmap.FromStream这样做,因为它的文档注释说

必须在图像的生命周期内保持流打开。

Image.FromFile的行为类似,它保持文件锁定,直到图像被处置。