Groups | Blog | Home
all groups > dotnet drawing api > october 2006 >

dotnet drawing api : MemoryStream and ImageFormat.Png problem?


OPL
10/11/2006 12:00:00 AM
I'm having a problem trying to read a bitmapped file into a memory stream
and then into a byte array.

Here's an example as to what I'm doing:

Bitmap bmp = new Bitmap(@"c:\windows\Soap Bubbles.bmp");
MemoryStream mem = new MemoryStream();
bmp.Save(mem, ImageFormat.Png);
byte[] imageArray = new byte[mem.Length];
int nRead = mem.Read(imageArray, 0, (int)mem.Length);

NB - There is no problem casting the length to an integer because we're only
looking at image of about 60kb in size. This problem is still apparant when
reading (, 1, 100).

What happens is that the memory stream is created with the right size, and
when the bitmap is saved the memory stream is filled with the saved byte
array as should be (this can be verified in VS2K5 by placing the cursor over
mem, going to "Non-public members" and looking at _buffer.

For some reason I can't read the internal array from the memory stream into
a byte array. No exception is thrown, but nRead is always 0, regardless of
how little or how much I try to read at once.

Ironically this works flawlessly when I have ImageFormat.Bmp. But I want the
images saved as PNG because I'm going to be loading several images into
memory.

Any ideas on what the problem is or a work-around?

Thanks!

jacky kwok
10/11/2006 12:00:00 AM
[quoted text, click to view]


You need to seek the current file position pointer in the MemoryStream
mem to begin before read ,


bmp.Save(mem, ImageFormat.Png);
/*the current file pointer at the end of stream*/

......
mem.Seek(0, SeekOrigin.Begin);
int nRead = mem.Read(imageArray, 0, (int)mem.Length);
.....

--
Jacky Kwok
jacky@alumni_DOT_cuhk_DOT_edu_DOT_hk
OPL
10/11/2006 12:00:00 AM
Hi Jacky.

Thanks heaps. That worked awesome. Any idea then why when using a Bitmap
it's fine without needing to seek back to the beginning?

Thanks.

[quoted text, click to view]

jacky kwok
10/11/2006 12:00:00 AM
[quoted text, click to view]

I think it is because the different behavior of the internal image encoder.

In fact, in case of Bmp format, after

bmp.Save(mem, ImageFormat.Bmp);

The file poition of the stream is not in the begin. In the debugger, I
found it was "2626" in the total stream length was "1381218" of my
testing image.

I think it is because of the encoder need to write some info to the
header in the final step.

Hence, in your original code,

bmp.Save(mem, ImageFormat.Bmp);
byte[] imageArray = new byte[mem.Length];
int nRead = mem.Read(imageArray, 0, (int)mem.Length);

even for Bmp format , the (nRead != mem.Length).



--
Jacky Kwok
jacky@alumni_DOT_cuhk_DOT_edu_DOT_hk
jacky@compose_DOT_com_DOT_hk


[quoted text, click to view]
AddThis Social Bookmark Button