English 中文(简体)
MemoryStream.Read不会将字节复制到缓冲区 - c#
原标题:
  • 时间:2008-12-17 21:52:07
  •  标签:

I don t really get it and it s driving me nuts. i ve these 4 lines:

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);

when debugging i can see the bytes values in imageStream. after imageStream.Read i check content of contentBuffer and i see only 255 values. i can t get why is it happening? there is nothing to do wrong in these few lines! if anyone could help me it would be greatly appreciated! thanks, agnieszka

最佳回答

尝试将imageStream.Position设置为0。当您写入MemoryStream时,它会在刚刚写入的字节之后移动Position,因此如果您尝试在那里读取,那里没有任何内容。

问题回答

你需要重置文件指针。

imageStream.Seek( 0, SeekOrigin.Begin );

否则,您正在从流的结尾读取。

加上

imageStream.Position = 0;

就在这之前:

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

你读取指令中的“0”代表着在内存流中的偏移位置,而不是起始位置。在流被加载后,位置位于末尾。你需要重置它到起始位置。

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);

只是使用

imageStream.ToArray()

它有效且更容易。





相关问题
热门标签