How to Convert an image into grayscale in C#

By FoxLearn 7/19/2024 2:14:35 AM   8.79K
You can convert an image to grayscale in a C# Windows Forms Application using the Bitmap class.

How to Convert an image into grayscale in C#

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.

// Load the image
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.

// C# convert the image to grayscale
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);
}

This code includes a Windows Forms application with a button to open an image file and display its grayscale version in a PictureBox. The MakeGrayscale method converts the image to grayscale pixel by pixel by averaging the RGB values and assigning the result to each channel.