Programming Microsoft Windows with C#
Changing the Bitmap Palette
On page 494 I discuss the read/write Palette property of the Image class.
This property returns an object of type ColorPalette,
which has two read-only properties, Flags (of type int) and Entries (of type Color[]). I suggest that there's no way to change the palette of an Image object.
Apparently, I didn't try enough ways to do it.
If img is an object of type Image,
and clr is an object of type Color,
this approach will not work:
img.Palette.Entries[i] = clr; // Won't work!
I think the problem with this statement involves the prohibition against setting a property of a property. This approach won't work either:
ColorPalette pal = img.Palette;
pal.Entries[i] = clr; // Won't work!
Instead, you must follow up the palette-setting code by setting the Palette property
to the pal object you first obtain:
ColorPalette pal = img.Palette;
pal.Entries[i] = clr;
....
img.Palette = pal; // The crucial statement
This PaletteChange.cs [rename file after download] program demonstrates this technique.
The program lets you load a bitmap,
and then creates a new 8 bit-per-pixel monochrome bitmap of the same size.
The ConvertToMonochrome method uses GetPixel to read pixels from the
existing bitmap and LockBits to write to the new bitmap.
(SetPixel won't work with indexed bitmaps.)
This program must be compiled with the unsafe compiler option.
© Charles Petzold, 2003
cp@charlespetzold.com
This page last updated June, 2003