Tutorial on Converting Images to Grayscale using C# by ra00l

Introduction

   In this tutorial, we will create a grayscale image from a colored one. To run this application, you will need to have .NET Framework 1.1 installed. Also, to be able to follow this tutorial, you will need Visual Studio .NET installed on your machine.

Creating the Program for GrayScale Image:

   The first thing we will need, before starting designing and coding our application will be a colored image. In the attached project, I’ve included an image on whitch I will work. It’s not necessary to use the same image, you are welcomed to use any image you like, as long as it’s colored. Now that we have an image, let’s start programming.

   We need to create a C# application. To do that, go to File -> New -> Project -> Visual C# Project -> Windows Application. Name the project GrayscaleImage(any other name will be fine). Drag and drop from the Toolbox(View -> Toolbox or Ctrl + Alt + X ) two PictureBox controls and a Button. Set the first PictureBox control’s Name property to pb_color, SizeMode to StretchImage. Set the second PictureBox Name property to pb_grayscale and SizeMode to StretchImage. Now, set the button’s Text property to Convert and it’s Name to btn_convert.

   Let’s add two more buttons. For the first button we’ll set the Text property to Load Image, and the Name to btn_load. The second button’s Name to btn_save and its Text to Save Image.  Here is how my interface looks so far:

   Don’t worry if yours doesn’t look the same. You can arrange the controls in any way you like.

   Now, before we get down to coding, I would like to explain a little about the images format, in general. An image has three channels: Red, Green and Blue. These channels represents different nuance of the above color. Put one over the other, they form all the known colors. For example, Red=0, Green=0, Blue=0 represents black and Red=255, Green=255, Blue=255 represents white.

   The basic way to create a grayscale image is to set the Red, Green, and Blue to the same value. To convert a pixel from any color to a grayscale color, you need to apply the following formulas:

Grayscale color(R) = [Color(R)+Color(G)+Color(B)]/3

Grayscale color(G) = [Color(R)+Color(G)+Color(B)]/3

Grayscale color(B) = [Color(R)+Color(G)+Color(B)]/3

And this is how we convert the image.

   Let’s get to coding. In the Design view, double-click the form’s surface. Visual Studio .NET will create a method called Form1_Load that will occur when our application is started. What we want to do here is disable all the buttons, except btn_load.

private void Form1_Load(object sender, System.EventArgs e){

btn_convert.Enabled=false;

btn_save.Enabled=false;

}

  Go back to Design view and double-click btn_load. We’ll have a method similar to this one:

private void btn_load_Click(object sender, System.EventArgs e){

}

In this method we will add the code to get the image from the user’s drive. We must now add an OpenFileDialog, that will help the user to choose a file. Also, we have to set a filter, to allow only image files to be selected ( image files are files that have an extension of either jpg, jpeg, bmp, gif and other formats ).

OpenFileDialog open = new OpenFileDialog();

open.Filter = “Image Files(*.jpg; *.jpeg; *.gif; *.bmp)|*.jpg; *.jpeg; *.gif; *.bmp”;

      The next step is to show the OpenFileDialog window, to allow the user to select a file. Now, we’ll also want to see what button the user clicked after selecting a file (OK or Cancel).

if (open.ShowDialog()==DialogResult.OK)

{

}

The ShowDialog method shows the control to the user. It also returns a DialogResult object to find out what button was pressed. To see if the user pressed the OK button, we compare the result to DialogResult.OK. If that happened, we should get the selected file and put it into the PictureBox. Also, we have to enable btn_convert to allow the conversion.

   Now we must create the code to convert the image to grayscale. Go to Design view and double-click btn_convert. Here we will create the code to convert the image.

private void btn_convert_Click(object sender, System.EventArgs e)

{

}

The first thing we need to do is create a copy of the color image. To do that, we need to create a Bitmap object.

Bitmap grays = (Bitmap)pb_color.Image;

   We have created a Bitmap object with the value of the original image. To convert it to grayscale, we must iterate through each pixel of the image and apply the algorithm described above. But first, we need to find out the size of the image.

int width = grays.Size.Width;

int height = grays.Size.Height;

Now we found out the width and height of the image, so let’s start converting.

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

{for (int i=0; i<width; i++)

{

   Color col;

col = grays.GetPixel(i, j);

grays.SetPixel (i,j,Color.FromArgb((col.R+col.G+col.B)/3,(col.R+col.G+col.B)/3,(col.R+col.G+col.B)/3));

}

}

   What we do is iterate through each pixel of our Bitmap, and set its color according to above algorithm.  The last things we need to do is set the PictureBox’s Image property to the new bitmap and enable the btn_save button.

pb_grayscale.Image = grays;

btn_save.Enabled=true;

Run the sample and see the code at work.

Note: You will see some images slightly distorted. This is because we’ve set a fixed size of the PictureBox object and “told” him to fit the image in it.

   A last thing we want to add is the possibility for the user to save the grayscale image into his hard-drive. Go to Design view and double-click btn_save. In the newly created method, add the following code:

Bitmap b = (Bitmap)pb_grayscale.Image;

SaveFileDialog save = new SaveFileDialog();

save.Filter = “Image Files(*.jpg; *.jpeg; *.gif; *.bmp)|*.jpg; *.jpeg; *.gif; *.bmp”;

if (save.ShowDialog()==DialogResult.OK)

{

b.Save(save.FileName);

}

First, we create a Bitmap from the pb_grayscale image. We then instantiate a SaveFileDialog object and add the same filter we added earlier. Then, we make the dialog visible, and check if the user presses OK button. If this happens, we save the image on the path and with the name chosen. Here is the program in action on my machine:

Well, that’s about it.

Until next time, I wish you luck and happy programming!

Raul POPESCU

Attachments:

   Project Files: GrayScale_sample.zip