Copy MemoryStream and recreate System.Drawing.Image fails with "Parameter is not valid"

StackOverflow https://stackoverflow.com/questions/18785292

  •  28-06-2022
  •  | 
  •  

سؤال

I am receiving an ArgumentException (Parameter is not valid) when trying to recreate an image from a memory stream. I have distilled it down to this example where I load up an image, copy to a stream, replicate the stream and attempt to recreate the System.Drawing.Image object.

im1 can be saved back out fine, after the MemoryStream copy the stream is the same length as the original stream.

I am assuming that the ArgumentException means that System.Drawing.Image doesnt think my stream is an image.

Why is the copy altering my bytes?

// open image 
var im1 = System.Drawing.Image.FromFile(@"original.JPG");


// save into a stream
MemoryStream stream = new MemoryStream();
im1.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);


// try saving - succeeds
im1.Save(@"im1.JPG");

// check length
Console.WriteLine(stream.Length);



// copy stream to new stream - this code seems to screw up my image bytes
byte[] allbytes = new byte[stream.Length];
using (var reader = new System.IO.BinaryReader(stream))
{
    reader.Read(allbytes, 0, allbytes.Length);
}
MemoryStream copystream = new MemoryStream(allbytes);



// check length - matches im1.Length
Console.WriteLine(copystream.Length);

// reset position in case this is an issue (doesnt seem to make a difference)
copystream.Position = 0;

// recreate image - why does this fail with "Parameter is not valid"?
var im2 = System.Drawing.Image.FromStream(copystream);

// save out im2 - doesnt get to here
im2.Save(@"im2.JPG");
هل كانت مفيدة؟

المحلول

Before reading from the stream you need to rewind its position to zero. You are doing that for the copy right now, but also need to do that for the original.

Also, you don't need to copy to a new stream at all.

I usually resolve such problems by stepping through the program and looking at runtime state to see whether it matches my expectation or not.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top