Convert an Image to Gray Scale in C#

Sometimes you need to take a color image and remove all of the color from it leaving just shades of gray. There are 3 common ways of performing this calculation, each yielding slightly different results.

  • The Lightness method
  • The Average method
  • The Luminosity method

They are all very easy to implement in C#. In this example we’ll use the Luminosity Method since that is the default method used in most image manipulation programs.

To convert an image to gray scale we need to look at each pixel, calculate the luminosity for that pixel, and set that pixels value so that each red, green, and blue are equal to the luminosity. The formula for luminosity is:

Luminosity = 0.21 R + 0.72 G + 0.07 B

In C# we need to store the luminosity as an integer, but the compiler is going to calculate it as a double, so we’re going to need to¬†convert it to an int. We’re using Convert.ToInt for the conversion, but you could use an (int) cast instead if you understand the difference.

Here’s the code to load an image, convert it to gray scale, and save the results as a PNG.

 Results of Convert to Gray Scale

Here are the results of converting to gray scale using luminosity.

Source Image


Output Image


You can see that the blue was turned to almost black. This is because blue has a very low coefficient in the luminosity equation.

Alternate Formula for Gray Scale

If you do not like the results of this conversion you can always change the luminosity formula to be a straight average. To do that replace this line:

With this:

This is called an “Average” formula because it takes the simple mathematical average of red, green, and blue and uses that value for the new components.

Other Image Processing Guides

If you like this guide you might want to check out some of our other C# Image Processing Guides.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.