Grayscale Image

Description: Takes in an image resource and returns it as a gray scale version of it.
Tested Platform: .NET 4.0, Visual Studio 2010, Windows 7
Language: C#
private Image GrayScale(ref Image source) {

    Bitmap bitMap = new Bitmap(source);

    using (Graphics g = Graphics.FromImage(bitMap)) {
        System.Drawing.Imaging.ColorMatrix matrix = new System.Drawing.Imaging.ColorMatrix(
            new float[][] 
            {
                new float[] {.3f, .3f, .3f, 0, 0},
                new float[] {.59f, .59f, .59f, 0, 0},
                new float[] {.11f, .11f, .11f, 0, 0},
                new float[] {0, 0, 0, 1, 0},
                new float[] {0, 0, 0, 0, 1}
            });

        System.Drawing.Imaging.ImageAttributes attributes = new System.Drawing.Imaging.ImageAttributes();
        attributes.SetColorMatrix(matrix);

        g.DrawImage(source, new Rectangle(0, 0, source.Width, source.Height), 0, 0, source.Width, source.Height, GraphicsUnit.Pixel, attributes);
    }

    return (Image)bitMap;
}

Submitted: October 23, 2012

Return to the snippets listing