簡體   English   中英

復制MemoryStream並重新創建System.Drawing.Image失敗,並顯示“參數無效”

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM