Saad A Saad A -3 years ago 142
C# Question

Byte Array to Image : Parameter is not valid

I am working with a electronic software OMICRON MPD and MI that provides a COM Interface. I am taking a screenshot via the methods provided by COM Interface and attempting to save the byte[] to an image file.

My code:

byte[] rawImg = ...
MemoryStream mstream = new MemoryStream(rawImg);
ImageConverter imageConverter = new System.Drawing.ImageConverter();
System.Drawing.Image image = imageConverter.ConvertFrom(rawImg) as System.Drawing.Image; //error line
image.Save(@"path\img.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);

I get the Error:

System.ArgumentException' occurred in System.Drawing.dll Parameter is not valid

I have checked the length of the byte array:


I can save the above memory stream to a file using the following:

using (FileStream file = new FileStream(@"path\img.txt", FileMode.Create, FileAccess.Write))

And it saves the file whose output is :

( õ À & & ôÿÿ ôÿÿ ôÿÿ ôÿÿ

Or in Nodepad++

enter image description here

The bytes I converted to hex and saved it to a text file and its first line is:


I am not sure what it means, but how do I debug this? Where is the error? Is it the data I am receiving that is erroneous or the C# code to save it as an image.

According to the COM Interface documentation, the rawImg is device-independent bitmap (the format is identical to a .BMP file).

Failed Attempt #1

ImageConverter imageConverter = new System.Drawing.ImageConverter();
Image image = imageConverter.ConvertFrom(rawImg) as Image; //error line
image.Save(@"path\img.bmp", System.Drawing.Imaging.ImageFormat.Bmp);

gives same error as above about invalid parameter

Answer Source

Looking at the Notepad++ dump it appears this is just the raw bytes of 32 bit-per-pixel or 4 byte ARGB image. You should be able to use the Bitmap(Int32, Int32, Int32, PixelFormat, IntPtr) constructor and just pass in the raw bytes. The only issue will be figuring out the width, height, stride, and PixelFormat of the image but you should be able to figure that out with a little bit of experimentation.

Here's an example where I made a byte array similar to the one you've shown:

byte[] bytes = new byte[] {

    fixed (byte* pBytes = bytes)
        int width = 4; // Your width
        int height = 2; // Your height
        int stride = width * 4; // Your stride
        Bitmap bitmap = new Bitmap(width, height, stride, PixelFormat.Format32bppArgb, new IntPtr(pBytes));
        bitmap.Save(@"c:\temp\bitmap.png"); // Could save to another format like .jpg
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download