1

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

1 に答える 1

2

から読み取る前に、streamその位置をゼロに巻き戻す必要があります。あなたは今、コピーに対してそれを行っていますが、オリジナルに対してもそれを行う必要があります。

また、新しいストリームにコピーする必要はまったくありません。

私は通常、このような問題を解決するために、プログラムをステップ実行し、実行時の状態を調べて、期待どおりかどうかを確認します。

于 2013-09-13T11:35:29.083 に答える