Color Transformation in C# GDI+ Programming - A Sample that Uses Color Transformation Matrices
(Page 3 of 4 )
The following example takes an image of ASTRO BOY, who is the dramatis personae in the famous Japanese film ASTRO BOY. We are to apply the color transformation matrix described in the preceding paragraphs to accomplish the following result:
Double the red component
Set the color saturation of the red component to 1
When you launch the sample application, you will get the screenshot shown in Figure 6.
Figure 6—the running time snapshot of the sample application

The image shown on the left of Figure 6 corresponds to the original image, while the right one relates to the transformed image.
Now, let’s take a thorough look at the related source code.
Graphics graphics = this.CreateGraphics();
//use white color to populate the background
graphics.Clear(Color.White);
//load the original picture
Bitmap image = new Bitmap("ASTROBOY.bmp");
int width = image.Width;
int height = image.Height;
//create an instance of class ImageAttributes
ImageAttributes imageAttributes = new ImageAttributes();
//define the color transformation matrix
float[][] colorMatrixElements =
{
new float[]{2.0f, 0.0f, 0.0f, 0.0f, 0.0f},
new float[] { 0.0f, 1.0f, 0.0f, 0.0f, 0.0f},
new float[] { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f},
new float[]{0.0f, 0.0f, 0.0f, 1.0f, 0.0f},
new float[]{1.0f, 0.0f, 0.0f, 0.0f, 1.0f}
};
ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements);
//enable the color transformation matrix
imageAttributes.SetColorMatrix(
colorMatrix,
ColorMatrixFlag.Default,
ColorAdjustType.Bitmap);
//first render the source image
//at the specified location (0, 0)
graphics.DrawImage(image, 0, 0);
//next render the target image using the
//color transformation matrix defined above
graphics.TranslateTransform(width + 10, 0);
graphics.DrawImage(
image,
new Rectangle(0, 0, width, height),
0, 0,
width, height, GraphicsUnit.Pixel,
imageAttributes);
On the whole, the code in the preceding example utilizes the following steps to render the target image:
Initialize a ColorMatrix structure.
Create an ImageAttributes object and pass the address of the ColorMatrix structure to the SetColorMatrix() method of the ImageAttributes object.
Pass the address of the ImageAttributes object to the Graphics::DrawImage() method of a Graphics object.
To present a more striking contrast to the previous sample, let’s check out another image (see Figure 7) that resembles the color matrix used in Adobe Photoshop.
Figure 7—the color matrix image comparison

That’s all for this simple sample.
Next: Conclusion >>
More C# Articles
More By Xianzhong Zhu