Windows Forms: Convert an image into grayscale in C#

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

To play the demo, you should 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#

Next, Handle your winform as the following code.

using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;

namespace ConvertImageToGray
{
    public partial class Form5 : Form
    {
        public Form5()
        {
            InitializeComponent();
        }

        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);
            }
        }

        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;
        }

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

First, 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#.