[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Use an ImageAttributes object to convert an image to shades of red, green, or blue in C#

convert an image to shades of red, green, or blue

This example uses the techniques described by Use an ImageAttributes object to adjust an image's brightness in C# to convert an image to shades of red, green, or blue. The previous example scaled each pixel's red, green, and blue color components by the same amount. This example scales two of the three components by a factor of 0 to knock them out. The result is a red, green, or blue scale image.

The following ScaleColorComponents method scales the red, green, and blue color components of an image.

// Scale an image's color components. private Bitmap ScaleColorComponents(Image image, float r, float g, float b, float a) { // Make the ColorMatrix. ColorMatrix cm = new ColorMatrix(new float[][] { new float[] {r, 0, 0, 0, 0}, new float[] {0, g, 0, 0, 0}, new float[] {0, 0, b, 0, 0}, new float[] {0, 0, 0, a, 0}, new float[] {0, 0, 0, 0, 1}, }); ImageAttributes attributes = new ImageAttributes(); attributes.SetColorMatrix(cm); // Draw the image onto the new bitmap while applying // the new ColorMatrix. Point[] points = { new Point(0, 0), new Point(image.Width, 0), new Point(0, image.Height), }; Rectangle rect = new Rectangle(0, 0, image.Width, image.Height); // Make the result bitmap. Bitmap bm = new Bitmap(image.Width, image.Height); using (Graphics gr = Graphics.FromImage(bm)) { gr.DrawImage(image, points, rect, GraphicsUnit.Pixel, attributes); } // Return the result. return bm; }

The key is the ColorMatrix object. It is similar to an identify matrix except the entry that scales the pixels' scaling components are set to scale the red, green, and blue color components. See the previous example for additional details about how the drawing part works.

The example uses the method as in the following code, which removes the green and blue components from the image.

picRed.Image = ScaleColorComponents(picOriginal.Image, 1, 0, 0, 1);

The program passes the method the values 0 and 1 to either remove a color component or leave it unchanged, but you can get some interesting results by using other values. For example, try the following code.

picRed.Image = ScaleColorComponents(picOriginal.Image, 1, 0, 1, 1);

Download the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.