How to: Use a Color Remap Table


Remapping is the process of converting the colors in an image according to a color remap table. The color remap table is an array of ColorMap objects. Each ColorMap object in the array has an OldColor property and a NewColor property.

When GDI+ draws an image, each pixel of the image is compared to the array of old colors. If a pixel's color matches an old color, its color is changed to the corresponding new color. The colors are changed only for rendering — the color values of the image itself (stored in an Image or Bitmap object) are not changed.

To draw a remapped image, initialize an array of ColorMap objects. Pass that array to the SetRemapTable method of an ImageAttributes object, and then pass the ImageAttributes object to the DrawImage method of a Graphics object.

The following example creates an Image object from the file RemapInput.bmp. The code creates a color remap table that consists of a single ColorMap object. The OldColor property of the ColorRemap object is red, and the NewColor property is blue. The image is drawn once without remapping and once with remapping. The remapping process changes all the red pixels to blue.

The following illustration shows the original image on the left and the remapped image on the right.

Color ReMap

        Image image = new Bitmap("RemapInput.bmp");
        ImageAttributes imageAttributes = new ImageAttributes();
        int width = image.Width;
        int height = image.Height;
        ColorMap colorMap = new ColorMap();

        colorMap.OldColor = Color.FromArgb(255, 255, 0, 0);  // opaque red
        colorMap.NewColor = Color.FromArgb(255, 0, 0, 255);  // opaque blue

        ColorMap[] remapTable = { colorMap };

        imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);

        e.Graphics.DrawImage(image, 10, 10, width, height);

           new Rectangle(150, 10, width, height),  // destination rectangle 
           0, 0,        // upper-left corner of source rectangle 
           width,       // width of source rectangle
           height,      // height of source rectangle

The preceding example is designed for use with Windows Forms, and it requires PaintEventArgse, which is a parameter of the Paint event handler.

Recoloring Images
Images, Bitmaps, and Metafiles