Over a million developers have joined DZone.

How to Convert an Image to Gray Scale With WPF

· Web Dev Zone

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

I've been playing with the Windows Presentation Foundation today and I had a task where I needed to convert an image to gray scale to do some image analysis on it. I've done this a bunch of times before using GDI methods or by accessing the BitmapData class in .NET. For this short post I'd like to demonstrate how to manipulate images using the WriteableBitmap class.

The easiest way to convert an image to gray scale is to set the RGB values of every pixel to the average of each pixels RBG values.

R = (R + B + G) / 3
G = (R + B + G) / 3
B = (R + B + G) / 3

Here's a code snippet for manipulating a BitmapSource object using the WriteableBitmap class into a gray scale image:

public unsafe static BitmapSource ToGrayScale(BitmapSource source)


    const int PIXEL_SIZE = 4;

    int width = source.PixelWidth;

    int height = source.PixelHeight;

    var bitmap = new WriteableBitmap(source);



    var backBuffer = (byte*)bitmap.BackBuffer.ToPointer();

    for (int y = 0; y < height; y++)


        var row = backBuffer + (y * bitmap.BackBufferStride);

        for (int x = 0; x < width; x++)


            var grayScale = (byte)(((row[x * PIXEL_SIZE + 1]) + (row[x * PIXEL_SIZE + 2]) + (row[x * PIXEL_SIZE + 3])) / 3);

            for (int i = 0; i < PIXEL_SIZE; i++)

                row[x * PIXEL_SIZE + i] = grayScale;



    bitmap.AddDirtyRect(new Int32Rect(0, 0, width, height));



    return bitmap;


Another way to to convert an image to gray scale is to set the RGB values of every pixel to the sum of 30% of the red value, 59% of the green value, and 11% of the blue value. Hope you find this useful.

Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.


Published at DZone with permission of Christian Helle, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}