Tuesday, November 02, 2004

How to create a 1-bit-per-pixel image from a true-color image in .NET

In .NET, the following code

Bitmap bmp = new Bitmap (160, 64);

creates a Bitmap object with the default pixel format Format32bppARGB. You can create a Bitmap object with a different pixel format as follows.

Bitmap bmp = new Bitmap (160, 64, PixelFormat.Format1bppIndexed);

After you have a Bitmap instance, you might want to call Graphics.FromImage to get a Graphics object so that you can draw on the Bitmap instance. According to SDK, this method throws an exception if the image has any ofthe following pixel formats.
· PixelFormat.Format1bppIndexed
· PixelFormat.Format4bppIndexed
· PixelFormat.Format8bppIndexed
· PixelFormat.Undefined
· PixelFormat.DontCare
· PixelFormat.Format16bppArgb1555
· PixelFormat.Format16bppGrayScale

So your best bet to get a Graphics object and have the minimal file size will be a 24-bit-per-pixel bitmap. That might not fulfill your requirements in term of the file size.

Here is one way I recommend. You first create a Bitmap object with the default pixel format, get a Graphics object, and draw the image as you need. Then you create a new Bitmap object with your desired pixel format, use Bitmap.LockBits to get an entry to the bitmap bytes, set pixels on the second bitmap according to the corresponding pixels on the first bitmap, and call Bitmap.UnlockBits to release the lock.

The following link shows how to create a 1-bit-per-pixel image from atrue-color image in .NET.

http://www.bobpowell.net/onebit.htm

You will need to lock the image data so that the GC doesn't move it around during a collection (and while you are moving around it).

I learnt this way from Fabian Schmied and Chris Anderson (Merak).

0 Comments:

Post a Comment

<< Home