The parameter is not valid when converting a byte array to an image

I want to save images in an access database, I used an OLE object.

The idea is to convert the image to an array of bytes, and then add an array of bytes to the database.

this is the function:

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

it works great.

When I want to return an array of bytes to an image, I get an exception:

Argument exception

Unhandled Invalid parameter.

I tried two functions to convert an array of bytes to an image:

    public static Image ImageFromByte(byte[] image)
    {
        ImageConverter ic = new ImageConverter();
        Image img = (Image)ic.ConvertFrom(image);//here the exception comes
        return img;
    }

OR

    public static Image ImageFromByte1(byte[] byteArrayIn)
    {
        MemoryStream ms = new MemoryStream(byteArrayIn);
        Image returnImage = Image.FromStream(ms);//here the exception comes
        return returnImage;
    }

What is the problem, how to fix it?

+4
source share
1 answer

, . .

- :

            string path = @"c:\myimage.jpg";
            using (MemoryStream inputStream = new MemoryStream(byteArrayIn))
            {
                using (Stream file = File.Create(path))
                {
                    byte[] buffer = new byte[8 * 1024];
                    int len;
                    while ((len = inputStream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        file.Write(buffer, 0, len);
                    }
                } 
            }

EDIT: , , . :

            using (MemoryStream inputStream = new MemoryStream(byteArrayIn))
            {
                using (var image = Image.FromStream(inputStream))
                {
                    // see if this works.
                    // handle the image as you wish, return it, process it or something else.
                } 
            }
+1

Source: https://habr.com/ru/post/1524127/


All Articles