views:

5083

answers:

5

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

+11  A: 

You need to reset the file pointer.

imageStream.Seek( 0, SeekOrigin.Begin );

Otherwise you're reading from the end of the stream.

Joel Lucsy
+10  A: 

Try setting imageStream.Position to 0. When you write to the MemoryStream it moves the Position after the bytes you just wrote so if you try to read there's nothing there.

Andrew Kennan
+4  A: 

Add:

imageStream.Position = 0;

right before:

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

the 0 in your read instruction stands for the offset from the current position in the memory stream, not the start of the stream. After the stream has been loaded, the position is at the end. You need to reset it to the beginning.

BenAlabaster
+3  A: 
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);
Daok
+2  A: 

Just use

imageStream.ToArray()

It works and it easier.

Jaime Bula