[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: Quickly convert an image to grayscale in C#


This example shows how you can quickly convert an image to grayscale by using the Bitmap32 class described in the post Use the Bitmap32 class to manipulate image pixels very quickly in C#. The ConvertBitmapToGrayscale method shown in the following code performs the conversion.

// Convert the Bitmap to grayscale. private void ConvertBitmapToGrayscale(Bitmap bm, bool use_average) { // Make a Bitmap24 object. Bitmap32 bm32 = new Bitmap32(bm); // Lock the bitmap. bm32.LockBitmap(); // Process the pixels. for (int x = 0; x < bm.Width; x++) { for (int y = 0; y < bm.Height; y++) { byte r = bm32.GetRed(x, y); byte g = bm32.GetGreen(x, y); byte b = bm32.GetBlue(x, y); byte gray = (use_average ? (byte)((r + g + b) / 3) : (byte)(0.3 * r + 0.5 * g + 0.2 * b)); bm32.SetPixel(x, y, gray, gray, gray, 255); } } // Unlock the bitmap. bm32.UnlockBitmap(); }

The code first makes a Bitmap32 object to manipulate the bitmap, and locks the object so it can start work.

The code then loops through the image's pixels. If the use_average parameter is true, then the code makes the new pixel's value be a simple average of the original pixel's color components. If use_average is false, the method uses a weighted average. In many cases you won't know the difference.

After it has processed the pixels, the code unlocks the Bitmap32 object.

The example program uses the method to display an average image (middle) and a weighted average image (right). That's all there is to it!

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

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