Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parameter is not valid when getting image from stream

Tags:

c#

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.

like image 305
duka1 Avatar asked Nov 25 '22 19:11

duka1


1 Answers

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.

like image 106
Quick Joe Smith Avatar answered Nov 28 '22 09:11

Quick Joe Smith