简体   繁体   中英

Parameter is not valid when getting image from stream

I have this code:

              MemoryStream ms = new MemoryStream(newbytes, 0,
            newbytes.Length);
              ms.Position = 0;      
        ms.Write(newbytes, 0, newbytes.Length);
              Image img = Image.FromStream(ms);
            img.Save(@"C:\Users\gsira\Pictures\Blue hills5.jpg");

I get this error at the Image.FromStream(ms) call:

System.ArgumentException: Parameter is not valid. at System.Drawing.Image.FromStream(Stream stream, Boolean useEmbeddedColorManagement, Boolean validateIma

How can I resolve this? A couple of links which solve this problem (one on an MSDN thread) are broken so I am lost.

If you initialise a MemoryStream with a byte array (which is what I am assuming newbytes to be), you should not need to write to it.

The call to Write(newbytes, 0, newbytes.Length) in your sample is completely redundant.

var s = new MemoryStream(newbytes, 0, newbytes.Length);
var i = Image.FromStream(s);

i.Save(@"C:\Users\gsira\Pictures\Blue hills5.jpg");

The above works for me where newbytes is a byte array of the contents of an image file on my hard drive.

Try to rewind memory stream to the very beginning after you wrote bytes into it.

ms.Seek(0, SeekOrigin.Begin);

Than it's possible to create Image.FromStream

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