Question

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

Was it helpful?

Solution

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.

OTHER TIPS

You need to reset the file pointer.

imageStream.Seek( 0, SeekOrigin.Begin );

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

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.

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

Just use

imageStream.ToArray()

It works and it easier.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top