Question

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. 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. now I want to update all the records, this time the ImagetoByte arrat method is throwing an exception as

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. Thank you..

Was it helpful?

Solution

The problem is that you close the underlying stream of the bitmap in byteArrayToImage when you dispose the MemoryStream.

You must not do this with Bitmap.FromStream as the remarks of the its documentation say

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top