Jan 4, 2011

Converting an image to grayscale in WinForms

A simple little helper static method to easily convert any image to its grayscale counterpart using older WinForms classes (System.Drawing namespace stuff).

public static Image ConvertToGrayscale(Image image)
Image grayscaleImage = new Bitmap(image.Width, image.Height, image.PixelFormat);

ImageAttributes attributes = new ImageAttributes();

// Red should be converted to (R*.299)+(G*.587)+(B*.114)
// Green should be converted to (R*.299)+(G*.587)+(B*.114)
// Blue should be converted to (R*.299)+(G*.587)+(B*.114)
// Alpha should stay the same.
ColorMatrix grayscaleMatrix = new System.Drawing.Imaging.ColorMatrix(new float[][]{
new float[] {0.299f, 0.299f, 0.299f, 0, 0},
new float[] {0.587f, 0.587f, 0.587f, 0, 0},
new float[] {0.114f, 0.114f, 0.114f, 0, 0},
new float[] { 0, 0, 0, 1, 0},
new float[] { 0, 0, 0, 0, 1}});

// Use a Graphics object from the new image
using (Graphics graphics = Graphics.FromImage(grayscaleImage))
// Draw the original image using the ImageAttributes we created
new Rectangle(0, 0, grayscaleImage.Width, grayscaleImage.Height),
0, 0, grayscaleImage.Width, grayscaleImage.Height,
GraphicsUnit.Pixel, attributes);

return grayscaleImage;

Note that the matrix I use is a fairly common one, but there are other ways depending on if you want a luminance-based or channel-based. It’s actually kinda interesting.

No comments:

Post a Comment