Converting Image to Black and White in C#

To make those weird pictures you have on your phone seem more dramatic.
Aug 29 2008 by James Craig

Ok, I lied about no code this week... I swear that one of these days I'll run out of bits of code to hand out, but anyway. Have you ever seen the various picture galleries out there that do a nice rollover effect where every image is in black and white until you roll over it. Thus you get a nice highlighting effect where the one you're on is color. You might think that you'd need to upload the two images but in reality, all you need to do is convert the one image to black and white. And without further ado, here's the code to accomplish it:

ColorMatrix.cs #

 /\*
Copyright (c) 2010 <a href="http://www.gutgames.com">James Craig</a>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.\*/

#region Usings
using System.Drawing;
using System.Drawing.Imaging;
#endregion

namespace Utilities.Media.Image
{
/// <summary>
/// Helper class for setting up and applying a color matrix
/// </summary>
public class ColorMatrix
{
#region Constructor

/// <summary>
/// Constructor
/// </summary>
public ColorMatrix()
{
}

#endregion

#region Properties

/// <summary>
/// Matrix containing the values of the ColorMatrix
/// </summary>
public float\[\]\[\] Matrix { get; set; }

#endregion

#region Public Functions

/// <summary>
/// Applies the color matrix
/// </summary>
/// <param name="OriginalImage">Image sent in</param>
/// <returns>An image with the color matrix applied</returns>
public Bitmap Apply(Bitmap OriginalImage)
{
Bitmap NewBitmap = new Bitmap(OriginalImage.Width, OriginalImage.Height);
using (Graphics NewGraphics = Graphics.FromImage(NewBitmap))
{
System.Drawing.Imaging.ColorMatrix NewColorMatrix = new System.Drawing.Imaging.ColorMatrix(Matrix);
using (ImageAttributes Attributes = new ImageAttributes())
{
Attributes.SetColorMatrix(NewColorMatrix);
NewGraphics.DrawImage(OriginalImage,
new System.Drawing.Rectangle(0, 0, OriginalImage.Width, OriginalImage.Height),
0, 0, OriginalImage.Width, OriginalImage.Height,
GraphicsUnit.Pixel,
Attributes);
}
}
return NewBitmap;
}

#endregion
}
}

ConvertBlackAndWhite Function #

 /// <summary>
/// Converts an image to black and white
/// </summary>
/// <param name="Image">Image to change</param>
/// <returns>A bitmap object of the black and white image</returns>
public static Bitmap ConvertBlackAndWhite(Bitmap Image)
{
ColorMatrix TempMatrix = new ColorMatrix();
TempMatrix.Matrix = 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}
};
return TempMatrix.Apply(Image);
}

The code is divided into two parts. The first is our ColorMatrix class. This class actually creates a new image (same size as the original), sets our color matrix based off of what it's told, tells GDI to convert the image using said color matrix, and then returns the resulting Bitmap object. That's all it's doing. The second part is our function which tells the class what to set for the actual color matrix. This portion might not be 100% clear, I mean what do the values in the color matrix mean?

A color matrix contains 5 different arrays. The first deals with the resultant red color, second array determines the resultant green, third determines blue, and the fourth determines alpha. The fifth array is a special translation array, basically deals with intensity of the colors. And each of those arrays contains red, blue, green, and alpha values in that order with values normally going from 0 to 1 (although you can go outside that range). So a default matrix would look like this:

 float\[\]\[\] FloatColorMatrix ={ 
new float\[\] {1, 0, 0, 0, 0},
new float\[\] {0, 1, 0, 0, 0},
new float\[\] {0, 0, 1, 0, 0},
new float\[\] {0, 0, 0, 1, 0},
new float\[\] {0, 0, 0, 0, 1}
};

This would give us exactly what we put in as the original image. What we're doing in the code above, is taking the average of red, green, and blue at different amounts in order to get the appropriate grey scale. The reason we're not simply using using .5 for all of them is actually due to the sensitivity of the human eye. Basically if you want to read about it, I'd suggest going here: GrayScale.

Also the code is a part of my utility library and thus any updates to the code can be found there. Anyway, hopefully that explains the only nonobvious portion of the code and will hopefully fit your needs. So copy it, try it out, leave feedback, and happy coding.