How To: Convert an Image to Grayscale#

Geee! it's been more than a month since I last posted something in this blog. I have been really really busy this past few weeks with a huge project and a gragantuan task which made it really hard for me to write anything that is interesting.

Anyway, I have been coding crazy as always when i found out that one of the Image Buttons in my project is missing a grayscale hover image. Whats crazy is that i didn't have Photoshop in my PC that time. The detail-oriented guy inside of me made the decision that i should have that image created because it is bothering me whenever i hover on an empty image placeholder.

And so, I was of to the races... Coding for just a mere button... After a couple of minutes I was able to convert the image to grayscale... with one problem... the button looks different from it's fellow buttons... Oh well! another useless idea :P

The complete Windows Application took a little over 5 minutes. Take a look at the core function below:

private Image ConvertImageToGrayScale(string sourceImageLocation)
{
   Image sourceImage = null;
   Bitmap bmp = null;
   try
   {
      //lets read our image
      sourceImage = Image.FromFile(sourceImageLocation);
      bmp = new Bitmap(sourceImage);

      //iterate through the pixels of the image starting from 0,0
      for (int xCoordinate = 0; xCoordinate < bmp.Width; xCoordinate++) {
         for (int yCoordinate = 0; yCoordinate < sourceImage.Height; yCoordinate++) {
            Color color = bmp.GetPixel(xCoordinate, yCoordinate);
            Color replacementColor = GetReplacementColor(color);

            //set the replacement color in the specified x and y coordinate
            bmp.SetPixel(xCoordinate, yCoordinate, replacementColor);
         }
      }

      sourceImage = (Image)bmp;
   }
   catch (Exception ex){
      string message = ex.Message;
      bmp.Dispose();
   }

   //return our grayscale image
   return sourceImage;
}

private Color GetReplacementColor(Color color)
{
   int redShade = (int)color.R;
   int blueShade = (int)color.B;
   int greenShade = (int)color.G;
   int shade = (redShade + blueShade + greenShade) / 3;
   return Color.FromArgb(shade, shade, shade);
}

Wednesday, December 06, 2006 12:50:41 AM (GMT Standard Time, UTC+00:00) #    Comments [0]  | 

 

Comments are closed.
All content © 2010, Keith Rull
On this page
This site
Calendar
<September 2010>
SunMonTueWedThuFriSat
2930311234
567891011
12131415161718
19202122232425
262728293012
3456789
Archives
Sitemap
Blogroll OPML
Disclaimer

Powered by: newtelligence dasBlog 2.3.9074.18820

The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

Send mail to the author(s) E-mail

Theme design by Jelle Druyts


Pick a theme: