Windows Forms: Convert an image into grayscale in C#

This post shows you how to Convert an image into grayscale in C# Windows Forms Application.

Creating a new Windows Forms Application project, then create a simple UI that allows you to open an image, then convert an image to black and white in c# as shown below.

convert an image into grayscale in c#

Adding a click event handler to the Open button that allows selecting an image file, then display an image into PictureBox control.

private void btnOpen_Click(object sender, EventArgs e)
{
    using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "Images|*.jpg" })
    {
        if (ofd.ShowDialog() == DialogResult.OK)
            picOriginal.Image = Image.FromFile(ofd.FileName);
    }
}

Next, Create a MakeGrayscale method allows you to convert an image into grayscale in c# as shown below.

public Bitmap MakeGrayscale(Bitmap original)
{
    Bitmap newBmp = new Bitmap(original.Width, original.Height);
    Graphics g = Graphics.FromImage(newBmp);
    ColorMatrix colorMatrix = new 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}
       });
    ImageAttributes img = new ImageAttributes();
    img.SetColorMatrix(colorMatrix);
    g.DrawImage(original, new Rectangle(0, 0, original.Width, original.Height), 0, 0, original.Width, original.Height, GraphicsUnit.Pixel, img);
    g.Dispose();
    return newBmp;
}

You need to create a new bitmap with size the same as image original, then create a color matrix and convert a color image to grayscale with C#.

Adding a click event handler to the Convert button that allows you to convert an image into grayscale 

private void btnConvert_Click(object sender, EventArgs e)
{
    picConvert.Image = MakeGrayscale((Bitmap)picOriginal.Image);
}