Convert an Image to Grayscale

gbertoli3 0 Tallied Votes 976 Views Share

Change a Color Image into a Grayscale(Black & White) Image.

/// <summary>
        /// Convert an Image to a Grayscale Image.
        /// </summary>
        /// <param name="Bitmap">The Bitmap to Convert to Grayscale.</param>
        /// <returns>A Grayscale Image.</returns>
        public static Bitmap Grayscale(Bitmap Bitmap)
        {
            //Declare myBitmap as a new Bitmap with the same Width & Height
            Bitmap myBitmap = new Bitmap(Bitmap.Width, Bitmap.Height);

            for (int i = 0; i < Bitmap.Width; i++)
            {
                for (int x = 0; x < Bitmap.Height; x++)
                {
                    //Get the Pixel
                    Color BitmapColor = Bitmap.GetPixel(i, x);

                    //Declare grayScale as the Grayscale Pixel
                    int grayScale = (int)((BitmapColor.R * 0.3) + (BitmapColor.G * 0.59) + (BitmapColor.B * 0.11));

                    //Declare myColor as a Grayscale Color
                    Color myColor = Color.FromArgb(grayScale, grayScale, grayScale);

                    //Set the Grayscale Pixel
                    myBitmap.SetPixel(i, x, myColor);
                }
            }
            return myBitmap;
        }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.