17

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

0

5 Answers 5

42

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.

Sign up to request clarification or add additional context in comments.

Comments

27

You need to reset the file pointer.

imageStream.Seek( 0, SeekOrigin.Begin );

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

Comments

15

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.

Comments

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

Comments

5

Just use

imageStream.ToArray()

It works and it easier.

1 Comment

ToArray() creates a new byte[] every time, thus creating garbage, sometimes that's just not okay

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.