[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 sepia tone in C#

convert an image to sepia tone

This example modified the previous example Use an ImageAttributes object to convert an image to monochrome in C# to convert an image to sepia tone.

This example uses a ColorMatrix that gives the resulting pixel's color components different values that move the color towards a brownish sepia color. If a pixel's original color components are R, G, and B, the the new component values are:

new_R = R * 0.393 + G * 0.769 + B * 0.189 new_G = R * 0.349 + G * 0.686 + B * 0.168 new_B = R * 0.272 + G * 0.534 + B * 0.131

The following ToSepiaTone method converts an image into sepia tone.

// Convert an image to sepia tone. private Bitmap ToSepiaTone(Image image) { // Make the ColorMatrix. ColorMatrix cm = new ColorMatrix(new float[][] { new float[] {0.393f, 0.349f, 0.272f, 0, 0}, new float[] {0.769f, 0.686f, 0.534f, 0, 0}, new float[] {0.189f, 0.168f, 0.131f, 0, 0}, new float[] { 0, 0, 0, 1, 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 values used to initialize the ColorMatrix convert the color components as desired. See the example Use an ImageAttributes object to adjust an image's brightness in C# for additional details about how the drawing part works.

This example converts an image to sepia tone, but you can get some interesting results by fiddling with the values in the ColorMatrix. For example, the following values make a sort of "violet tone."

ColorMatrix cm = new ColorMatrix(new float[][] { new float[] {0.300f, 0.066f, 0.300f, 0, 0}, new float[] {0.500f, 0.350f, 0.600f, 0, 0}, new float[] {0.100f, 0.000f, 0.200f, 0, 0}, new float[] { 0, 0, 0, 1, 0}, new float[] { 0, 0, 0, 0, 1} });

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

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