[英]Copy MemoryStream and recreate System.Drawing.Image fails with “Parameter is not valid”
尝试从内存流中重新创建图像时,我收到ArgumentException(参数无效)。 我将其精炼到此示例,在该示例中加载图像,复制到流,复制流并尝试重新创建System.Drawing.Image对象。
im1可以保存回来,在MemoryStream复制之后,流的长度与原始流的长度相同。
我假设ArgumentException意味着System.Drawing.Image不认为我的流是图像。
为什么副本会更改我的字节?
// 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");
从stream
读取之前,您需要将其位置倒回零。 您现在正在为副本执行此操作,但还需要为原始文档执行此操作。
另外,您根本不需要复制到新流。
我通常通过单步执行程序并查看运行时状态以查看其是否符合我的期望来解决此类问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.