Accessing the pixel data in a C# Bitmap class

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi,

I'm combining the pixels from 2 Bitmap classes, one is an overlay onto the
other. I'm currentlly doing it this way, using C#:

// Copy the overlay data onto the image file.
Color OverlayPixel;
for( int i = 0; i < PngImage.Width; i++)
for( int j = 0; j < PngImage.Height; j++)
{
OverlayPixel = PngOverlay.GetPixel( i, j);
if( OverlayPixel != System.Drawing.Color.Black)
{
PngImage.SetPixel( i, j, OverlayPixel);
}
}

This works, but is horribly slow, and will get even more so when I end up
doing this on larger images.

I believe this would go significantly faster if I worked on the pixel data
directly instead of going through GetPixel & SetPixel methods. Is there a
way to get the pixel data in a Bitmap class into a byte array?

Thanks Bruce
 
Hi Bruce,

Unfortunately, you can not access the internal bitmap structure on .NET CF.

However if you create your merged bitmap as an array, you can create a .NET
CF bitmap from that array with the following code.

byte[] bitmapData = new byte[ size ];

// Combine to bitmaps into bitmapData here

MemoryStream memStream = new MemoryStream(bitmapData);

Bitmap bmp = new Bitmap(memStream);

Thanks

Ercan
 
Hi Ercan,

Thanks for the reply,

That looks like a nice way to get an array of bytes into a bitmap. But
before I can do that, I need to get the pixel data out as an array of bytes
so I can effeciently merge them. The two bitmaps come from 2 *.png fies that
I load into two bitmap classes. I was hoping there was a way to extract the
bitmap data in the class into a byte array, because I really don't want to
write my own *.png file reader.

Bruce
 
BMP formated files may be easier to work with and you may find more
information on BMP format.The array should be arranged just like a BMP file.

There is another option which requires native programming.
1) You can load bitmaps,
2) Paint them to a device context using BitBlt etc
3) Implement an inherit managed stream class which will p/invoke to some
native functions for retrieving the bitmap.

Sorry this is my last silver bullet for this problem :(

- Ercan
 
Back
Top