How to Grayscale a bitmap

Will be posting article on how to create simple application, with full working code in C#
And welcome to anyone who want to post their own article
Post Reply
User avatar

Topic author
Superl
Site Admin
Site Admin
Posts: 1266
Joined: Sat Apr 16, 2011 7:49 am
Location: Montreal, Canada
Contact:

How to Grayscale a bitmap

#2278

Post by Superl » Sat Dec 19, 2015 6:05 am

Grayscale a bitmap

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

  1. /// <summary>
  2. /// Convert an Image to a Grayscale Image.
  3. /// </summary>
  4. /// <param name="Bitmap">The Bitmap to Convert to Grayscale.</param>
  5. /// <returns>A Grayscale Image.</returns>
  6. public static Bitmap Grayscale(Bitmap bitmap)
  7. {
  8.        //Declare myBitmap as a new Bitmap with the same Width & Height
  9.       Bitmap myBitmap = new Bitmap(bitmap.Width, bitmap.Height);
  10.  
  11.       for (int i = 0; i < bitmap.Width; i++)
  12.       {
  13.             for (int x = 0; x < bitmap.Height; x++)
  14.             {
  15.                   //Get the Pixel
  16.                   Color BitmapColor = bitmap.GetPixel(i, x);
  17.  
  18.                   //Declare grayScale as the Grayscale Pixel
  19.                   int grayScale = (int)((BitmapColor.R * 0.3) + (BitmapColor.G * 0.59) + (BitmapColor.B * 0.11));
  20.  
  21.                   //Declare myColor as a Grayscale Color
  22.                   Color myColor = Color.FromArgb(grayScale, grayScale, grayScale);
  23.  
  24.                   //Set the Grayscale Pixel
  25.                   myBitmap.SetPixel(i, x, myColor);
  26.             }
  27.       }
  28.       return myBitmap;
  29. }


Come and say hello in here
Any donation will help click here please.

Have a nice day :103:

Post Reply

Return to “Coding Forum”

Who is online

Users browsing this forum: No registered users and 1 guest