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);
}
Posted
12-05-2006 4:51 PM
by
keithrull