简体   繁体   中英

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

字节图像

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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM