2008-12-17 41 views
17

我真的不明白它和它的駕駛我堅果。 我這4行:MemoryStream.Read不復制字節緩存 - C#

Image img = Image.FromFile("F:\\Pulpit\\soa.bmp"); 
MemoryStream imageStream = new MemoryStream(); 
img.Save(imageStream, ImageFormat.Bmp); 
byte[] contentBuffer = new byte[imageStream.Length]; 
imageStream.Read(contentBuffer, 0, contentBuffer.Length); 

調試時我可以看到在的ImageStream字節值。 imageStream.Read之後,檢查contentBuffer的內容,我只看到255個值。 我無法得到它爲什麼發生?在這幾行中沒有任何錯誤! 如果有人可以幫助我將不勝感激! 謝謝, agnieszka

+4

4行?我在那裏數了5。 – 2010-09-10 04:17:52

回答

38

嘗試當你寫它移到你剛纔寫的,所以如果你嘗試閱讀沒有什麼存在的字節後的位置將MemoryStream設置imageStream.Position爲0。

25

您需要重置文件指針。

imageStream.Seek(0, SeekOrigin.Begin); 

否則,您正在從流尾讀取。

12

地址:

imageStream.Position = 0; 

權之前:

imageStream.Read(contentBuffer, 0, contentBuffer.Length); 

在讀指令的0代表從內存流中的當前位置,而不是流的開始的偏移量。流加載完成後,位置在最後。您需要將其重置爲開始。

8
Image img = Image.FromFile("F:\\Pulpit\\soa.bmp"); 
MemoryStream imageStream = new MemoryStream(); 
img.Save(imageStream, ImageFormat.Bmp); 
byte[] contentBuffer = new byte[imageStream.Length]; 
imageStream.Position = 0;//Reset the position at the start 
imageStream.Read(contentBuffer, 0, contentBuffer.Length); 
5

只需使用

imageStream.ToArray() 

它的工作原理,它更容易。