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