简体   繁体   English

复制MemoryStream并重新创建System.Drawing.Image失败,并显示“参数无效”

[英]Copy MemoryStream and recreate System.Drawing.Image fails with “Parameter is not valid”

I am receiving an ArgumentException (Parameter is not valid) when trying to recreate an image from a memory stream. 尝试从内存流中重新创建图像时,我收到ArgumentException(参数无效)。 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. 我将其精炼到此示例,在该示例中加载图像,复制到流,复制流并尝试重新创建System.Drawing.Image对象。

im1 can be saved back out fine, after the MemoryStream copy the stream is the same length as the original stream. im1可以保存回来,在MemoryStream复制之后,流的长度与原始流的长度相同。

I am assuming that the ArgumentException means that System.Drawing.Image doesnt think my stream is an image. 我假设ArgumentException意味着System.Drawing.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. stream读取之前,您需要将其位置倒回零。 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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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