13

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.

Xaruth
  • 4,034
  • 3
  • 19
  • 26

10 Answers10

10

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.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
supernorbert
  • 101
  • 1
  • 3
4

Maybe the image is embedded in an OLE field and you have to consider the 88 bytes OLE header plus payload:

byteBlobData = (Byte[]) reader.GetValue(0);
stream = new MemoryStream(byteBlobData, 88, byteBlobData.Length - 88);
img = Image.FromStream(stream);
3

I've had this problem when doing this:

MemoryStream stream = new MemoryStream();
screenshot.Save(stream, ImageFormat.Png);
byte[] bytes = new byte[stream.Length];
stream.Save(bytes, 0, steam.Length);

With the last 2 lines being the problem. I fixed it by doing this:

MemoryStream stream = new MemoryStream();
screenshot.Save(stream, ImageFormat.Png);
byte[] bytes = stream.ToArray();

And then this worked:

MemoryStream stream = new MemoryStream(bytes);
var newImage = System.Drawing.Image.FromStream(stream);
stream.Dispose();
NotDan
  • 31,709
  • 36
  • 116
  • 156
3

I'm guessing that something is going wrong when receiving the file from the server. Perhaps you're only getting part of the file before trying to convert it to an Image? Are you sure it's the exact same byte array you're feeding the C++ application?

Try saving the stream to a file and see what you get. You might be able to uncover some clues there.

You can also add a breakpoint and manually compare some of the bytes in the byte array to what they're supposed to be (if you know that).


Edit: It looks like there's nothing wrong with receiving the data. The problem is that it's in raw format (not a format that Image.FromStream understands). The Bitmap(Int32, Int32, Int32, PixelFormat, IntPtr) constructor may be of use here. Or, you can create the blank bitmap and blt it manually from the raw data.

lc.
  • 113,939
  • 20
  • 158
  • 187
  • Hello, I tried saving the image to a jpg, bmp file but i don't get the picture in the file. What is puzzling is that it is with the same byte array that i am able to display image in my VC++ MFC application. –  Mar 24 '09 at 03:59
  • That's why I'm not so sure it's the same byte array. Are the file sizes the same? – lc. Mar 24 '09 at 04:01
  • The VC++ application displays live images from the camera and therefore what i did was writing the byte array to a txt file. Similarly, from my .NET appln i wrote the byte array to a file nad then compared these two files. I find that all the values are filled and they are more or less the same. –  Mar 24 '09 at 04:06
  • Infact, i tried feeding the array i got from VC++ application (in txt file) to my C#.NET application. This failed too :-( –  Mar 24 '09 at 04:07
  • The byte array will not be same everytime due to intensity fluctuations of light falling on camera's lens. So, what i observed was some minor variations in byte array values between VC++ log and C# log –  Mar 24 '09 at 04:18
  • Maybe your C++ code just paint the camera's captured image directly on the screen, so it is not a formatted image (e.g. Jpg, png, bmp, etc), hence Image.FromStream could not work – Michael Buen Mar 24 '09 at 04:39
  • The camera send raw data which is of no format(no compression). –  Mar 24 '09 at 04:41
  • Hello Michael, Yes, you are right. The image array is not formatted. How do i proceed in that case ? Please help –  Mar 24 '09 at 04:43
  • Btw, is it a text file, as in ascii-readable text? Or just .txt file extension? Also try to check the file marker, if it is indeed a valid image format – Michael Buen Mar 24 '09 at 04:45
  • Try copy paste, i tried that approach with the raw image i get from camera in vb6 using winapi component, luckily the vb6 image control has paste method. Maybe .net image control has paste method too – Michael Buen Mar 24 '09 at 04:50
  • Hi Michael Buen, It is just a .txt file extension with byte array values in human readable format. What is this copy paste approach using winapi component ? Could you kindly elaborate in little more detail since i am not aware of it ? –  Mar 24 '09 at 04:54
  • try this: http://channel9.msdn.com/forums/TechOff/93476-Programatically-Using-A-Webcam-In-C/ using api from windows built-in avicap32.dll http://weblogs.asp.net/nleghari/articles/webcam.aspx – Michael Buen Mar 24 '09 at 06:01
1

Try this:

public Image byteArrayToImage(byte[] item)
{          
   Image img=Image.FromStream(new MemoryStream(item)); 
   img.Save(Response.OutputStream, ImageFormat.Gif);
   return img;
}

Hope it helps!

Zaheer Ul Hassan
  • 771
  • 9
  • 24
1

System.InvalidArgument means The stream does not have a valid image format, i.e. an image type that is not supported.

Mitch Wheat
  • 295,962
  • 43
  • 465
  • 541
  • 1
    Hello, Thanks for the reply. But how come the same byte array works in my VC++ MFC application ? Also is there any way i could check the validity of my byte array image data ? Arvind K –  Mar 24 '09 at 03:52
0

this code is working

        string query="SELECT * from gym_member where Registration_No ='" + textBox9.Text + "'";

        command = new SqlCommand(query,con);
        ad = new SqlDataAdapter(command);
        DataTable dt = new DataTable();
        ad.Fill(dt);
        textBox1.Text = dt.Rows[0][1].ToString();
        textBox2.Text = dt.Rows[0][2].ToString();
        byte[] img = (byte[])dt.Rows[0][18];
        MemoryStream ms = new MemoryStream(img);

        pictureBox1.Image = Image.FromStream(ms);
        ms.Dispose();
Daniel
  • 4,033
  • 4
  • 24
  • 33
0

Try to use something similar to what is described here https://social.msdn.microsoft.com/Forums/vstudio/en-US/de9ee1c9-16d3-4422-a99f-e863041e4c1d/reading-raw-rgba-data-into-a-bitmap

Image ImageFromRawBgraArray(
    byte[] arr, 
    int charWidth, int charHeight,
    int widthInChars, 
    PixelFormat pixelFormat)
{
    var output = new Bitmap(width, height, pixelFormat);
    var rect = new Rectangle(0, 0, width, height);
    var bmpData = output.LockBits(rect, ImageLockMode.ReadWrite, output.PixelFormat);

    // Row-by-row copy
    var arrRowLength = width * Image.GetPixelFormatSize(output.PixelFormat) / 8;
    var ptr = bmpData.Scan0;
    for (var i = 0; i < height; i++)
    {
        Marshal.Copy(arr, i * arrRowLength, ptr, arrRowLength);
        ptr += bmpData.Stride;
    }

    output.UnlockBits(bmpData);
    return output;
}
Andrey Belykh
  • 2,578
  • 4
  • 32
  • 46
0

After load from DataBase byteArray has more byte than one image. In my case it was 82.

MemoryStream ms = new MemoryStream();
ms.Write(byteArray, 82, byteArray.Length - 82);
Image image = Image.FromStream(ms);

And for save in the DB I insert 82 byte to begin stream. Properties.Resources.ImgForDB - it is binary file that contain those 82 byte. (I get it next path - Load Image from DB to MemoryStream and save to binary file first 82 byte. You can take it here - https://yadi.sk/d/bFVQk_tdEXUd-A)

        MemoryStream temp = new MemoryStream();
        MemoryStream ms = new MemoryStream();
        OleDbCommand cmd;
        if (path != "")
        {
            Image.FromFile(path).Save(temp, System.Drawing.Imaging.ImageFormat.Bmp);
            ms.Write(Properties.Resources.ImgForDB, 0, Properties.Resources.ImgForDB.Length);
            ms.Write(temp.ToArray(), 0, temp.ToArray().Length);

        cmd = new OleDbCommand("insert into Someone (first, Second, Third) values (@a,@b,@c)", connP);
        cmd.Parameters.AddWithValue("@a", fio);
        cmd.Parameters.AddWithValue("@b", post);
        cmd.Parameters.AddWithValue("@c", ms.ToArray());
        cmd.ExecuteNonQuery();
0

I've had the same problem in the past and it was caused by a leak within the windows GDI libraries, which is what 'Bitmap' uses. If this happening all the time for you then its probably unrelated, however.

Chris
  • 39,719
  • 45
  • 189
  • 235
  • Hello Chris, Thanks for the reply. It happens to me everytime i run the code. –  Mar 24 '09 at 03:57