ismail baig
ismail baig

Reputation: 891

byte array to image save throws an error like "Parameter not valid" in C#

i could see this question is asked many many times but none seems to be straight forward answer. so am posting this question.

I am reading BLOB from oracle database into photoByteArray[] array. Now i just want to save this byte[] into file systems as anyFileName.jpeg (or any format), but i get the "Parameter not vaid" exception.

What i tried is

using (var ms = new System.IO.MemoryStream(photoByteArray))
{
  using (var img = Image.FromStream(ms)) // error thrown here as 'parameter is not valid'
    {
      img.Save("D:\\anyFileName.jpg", ImageFormat.Jpeg); 
     }
 }

My bytes

Byte image

Few are suggesting that some header gets added in the byte array, but how and howmuch to remove that kind of header is not straight forward way.

What am i doing wrong ?

Upvotes: 0

Views: 2551

Answers (1)

vahid kargar
vahid kargar

Reputation: 794

When I use something like this:

Image img = Image.FromFile(@"C:\a.png");
            byte[] arr;
            using (MemoryStream ms = new MemoryStream())
            {
                img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                arr = ms.ToArray();
            }
            using (var ms = new System.IO.MemoryStream(arr))
            {
                using (var img1 = Image.FromStream(ms,false,true)) // error thrown here as 'parameter is not valid'
                {
                    img1.Save("D:\\anyFileName.png", ImageFormat.Png);
                }
            }

which convert an image file to byte and with your method convert that byte array to image it works properly.

but when I change some byte of that byteArray to 0 (zero)(for example first 15 bytes) I get your error.

so It is concluded that your byte array really isn't in correct format, some probabilities are:

  1. you are saving your byte array to your database with mistakes(for
    example datatype of your column is not appropriate).
  2. while getting byte array from DB you make some mistakes.
  3. some other reasons which I don't know.

Upvotes: 4

Related Questions