简体   繁体   English

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

[英]Convertion faild from Image to Byte array using ImageConverter in c#

I am converting my Image from picturebox to byte array as 我正在将我的图像从图片框转换为字节数组

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

and then conveting the byte array to image as 然后将字节数组视为图像

  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; }
    }

Here for the first time before I save the data, I am uploading the file from local system to the picture box as 在我保存数据之前,这是我第一次将文件从本地系统上传到图片框,如下所示:

       openFileDialog1.Filter = "JPG Files (*.jpg)|*.jpg|JPEG Files (*.jpeg)|*.jpeg";
        if (openFileDialog1.ShowDialog() != DialogResult.Cancel)
        {

            Image pic = Image.FromFile(openFileDialog1.FileName);
            pboxPhoto.Image = pic;
        }

It is working 100% for the 1st time I am saving the data to database. 第一次将数据保存到数据库时,它正在100%工作。 When I retrive the data I am converting the data from retrived byte array to Image and attaching to picturebox.Everything is ok until now. 当我检索数据时,我正在将数据从检索的字节数组转换为Image并附加到picturebox。到目前为止一切都还可以。 now I want to update all the records, this time the ImagetoByte arrat method is throwing an exception as 现在我想更新所有记录,这一次ImagetoByte arrat方法将引发异常

A generic error occurred in GDI+.

So my problem is when I upload the image from local system is converting but when I convert the byte array to Image and then try to convert the image to byte array, the method throwing above exception . 所以我的问题是当我从本地系统上传图像时正在转换,但是当我将字节数组转换为Image然后尝试将图像转换为字节数组时,该方法抛出上述异常 Thank you.. 谢谢..

The problem is that you close the underlying stream of the bitmap in byteArrayToImage when you dispose the MemoryStream . 问题是,当您处置MemoryStream时,您将关闭byteArrayToImage位图的基础流。

You must not do this with Bitmap.FromStream as the remarks of the its documentation say 您不能使用Bitmap.FromStream来执行此操作,因为其文档中的注释是

You must keep the stream open for the lifetime of the Image. 您必须在图像的生命周期内保持流打开。

Image.FromFile behaves similarly, it keeps the file locked until the image is disposed. Image.FromFile行为类似,它将保持文件锁定直到图像被释放为止。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM