Click here to Skip to main content
15,891,033 members

Response to: Converting Bitmap to grayscale

Revision 2
You'll find this tutorial helpful as it shows three different ways to do what you want. The last is my favorite and does its trick by using a ColorMatrix: http://www.switchonthecode.com/tutorials/csharp-tutorial-convert-a-color-image-to-grayscale[^]!

Hope this helps you!

Modification
Code sample: All you need to create is a form with a PictureBox on it!

C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace GrayImage
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
       
            //Load an image frim you local file system
            Image normalImage = Image.FromFile(@"D:\Data\Media\Photo\2009\25-12-2009\DSC_0073.jpg");
            // Turn image into gray scale image
            Image grayScaled = (Image)MakeGrayscale3(new Bitmap(normalImage));
            
            pictureBox1.BackgroundImageLayout = ImageLayout.Zoom;
            // Assign image to picture box
            pictureBox1.BackgroundImage = grayScaled;
        }

        // This is the method form the Web site I told you about
        public static Bitmap MakeGrayscale3(Bitmap original)
        {
            //create a blank bitmap the same size as original
            Bitmap newBitmap = new Bitmap(original.Width, original.Height);
            //get a graphics object from the new image
            Graphics g = Graphics.FromImage(newBitmap);
            //create the grayscale ColorMatrix
            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}
              });
            //create some image attributes
            ImageAttributes attributes = new ImageAttributes();
            //set the color matrix attribute
            attributes.SetColorMatrix(colorMatrix);
            //draw the original image on the new image
            //using the grayscale color matrix
            g.DrawImage(original, new Rectangle(0, 0, original.Width, original.Height),
               0, 0, original.Width, original.Height, GraphicsUnit.Pixel, attributes);
            //dispose the Graphics object
            g.Dispose();
            return newBitmap;
        }
    }
}


Best Regards,
Manfred
Posted 17-Jan-11 11:50am by Manfred Rudolf Bihy.
Tags: