Image.FromStream() method returns Invalid Argument exception

Arvind K picture Arvind K · Mar 24, 2009 · Viewed 45.2k times · Source

I am capturing images from a smart camera imager and receiving the byte array from the camera through socket programming (.NET application is the client, camera is the server).

The problem is that i get System.InvalidArgument exception at runtime.

private Image byteArrayToImage(byte[] byteArray) 
{
    if(byteArray != null) 
    {
        MemoryStream ms = new MemoryStream(byteArray);
        return Image.FromStream(ms, false, false); 
        /*last argument is supposed to turn Image data validation off*/
    }
    return null;
}

I have searched this problem in many forums and tried the suggestions given by many experts but nothing helped.

I dont think there is any problem with the byte array as such because When i feed the same byte array into my VC++ MFC client application, i get the image. But this doesn't somehow work in C#.NET.

Can anyone help me ?

P.S :

Other methods i've tried to accomplish the same task are:

1.

private Image byteArrayToImage(byte[] byteArray)
{
    if(byteArray != null) 
    {
        MemoryStream ms = new MemoryStream();
        ms.Write(byteArray, 0, byteArray.Length);
        ms.Position = 0; 
        return Image.FromStream(ms, false, false);
    }
    return null;
}

2.

private Image byteArrayToImage(byte[] byteArray) 
{
    if(byteArray != null) 
    {
        TypeConverter tc = TypeDescriptor.GetConverter(typeof(Bitmap));
        Bitmap b = (Bitmap)tc.ConvertFrom(byteArray);
        return b;
    }
    return null;
}

None of the above methods worked. Kindly help.

Answer

supernorbert picture supernorbert · Oct 9, 2013

Image.FromStream() expects a stream that contains ONLY one image!

It resets the stream.Position to 0. I've you have a stream that contains multiple images or other stuff, you have to read your image data into a byte array and to initialize a MemoryStream with that:

Image.FromStream(new MemoryStream(myImageByteArray));

The MemoryStream has to remain open as long as the image is in use.

I've learned that the hard way, too.