メモリ ストリームからイメージを再作成しようとすると、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");