ColorPalette Class (GDI+)
Overview
The ColorPalette class defines a set of colors that can be used with indexed pixel formats. It provides a way to retrieve and modify the colors in a palette that is associated with a Bitmap object.
Syntax
public sealed class ColorPalette
{
public int Flags { get; set; }
public int Count { get; }
public Color[] Entries { get; set; }
}
Constructors
Instances of ColorPalette are created by GDI+ when you call Bitmap.Palette. Direct construction is not supported.
Properties
- Flags – Reserved for future use.
- Count – Gets the number of colors in the palette (read‑only).
- Entries – Gets or sets the array of
Colorobjects that make up the palette.
Methods
The ColorPalette class does not expose methods; interaction is through its properties.
Example
This example creates a 256‑color palette, assigns it to a bitmap, and draws a gradient using the palette.
using System;
using System.Drawing;
using System.Drawing.Imaging;
class PaletteDemo
{
static void Main()
{
Bitmap bmp = new Bitmap(256, 100, PixelFormat.Format8bppIndexed);
ColorPalette pal = bmp.Palette;
for (int i = 0; i < pal.Entries.Length; i++)
{
int r = i;
int g = 255 - i;
int b = (i > 127) ? i - 127 : 127 - i;
pal.Entries[i] = Color.FromArgb(r, g, b);
}
bmp.Palette = pal;
BitmapData data = bmp.LockBits(new Rectangle(0,0,256,100), ImageLockMode.WriteOnly, bmp.PixelFormat);
unsafe
{
byte* ptr = (byte*)data.Scan0;
for (int y = 0; y < 100; y++)
for (int x = 0; x < 256; x++)
ptr[y * data.Stride + x] = (byte)x;
}
bmp.UnlockBits(data);
bmp.Save("palette_gradient.png", ImageFormat.Png);
}
}
Remarks
- The number of entries in
Entriesmust match the pixel format's color depth. - After modifying the palette, assign it back to the bitmap to apply changes.
- Indexed bitmaps are less common in modern applications but useful for memory‑constrained scenarios.