【问题标题】:Copy MemoryStream and recreate System.Drawing.Image fails with "Parameter is not valid"复制 MemoryStream 并重新创建 System.Drawing.Image 失败并显示“参数无效”
【发布时间】:2013-09-18 01:56:37
【问题描述】:

我在尝试从内存流重新创建图像时收到 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");

【问题讨论】:

  • 是否提供内部异常?

标签: c# .net stream memorystream


【解决方案1】:

在读取stream 之前,您需要将其位置倒回零。您现在正在为副本执行此操作,但也需要为原始执行此操作。

此外,您根本不需要复制到新的流中。

我通常通过单步执行程序并查看运行时状态以查看它是否符合我的预期来解决此类问题。

【讨论】:

  • 但是如果还需要复制,可以使用代码 var copyStream = new MemoryStream(stream.ToArray());
  • 或者,如果正在播放一般流,请使用 Stream.Copy。不需要 BinaryReader。
猜你喜欢
  • 2012-02-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-16
  • 2019-01-01
  • 2012-06-15
相关资源
最近更新 更多