Other Posts in Image Editing

  1. Perlin Noise
  2. Fault Formation
  3. Cellular Textures
  4. Resizing an Image in C#
  5. Box Blur and Gaussian Blur... Sort of...
  6. Thermal Erosion
  7. Using Mid Point Displacement to Create Cracks
  8. Fluvial Erosion
  9. Creating Marble Like Textures Procedurally
  10. Procedural Textures and Dilation
  11. Converting Image to Black and White in C#
  12. Getting an HTML Based Color Palette from an Image in C#
  13. Adding Noise/Jitter to an Image in C#
  14. Creating Pixelated Images in C#
  15. Edge detection in C#
  16. Using Sin to Get What You Want... In C#...
  17. Noise Reduction of an Image in C# using Median Filters
  18. Image Dilation in C#
  19. Sepia Tone in C#
  20. Kuwahara Filter in C#
  21. Matrix Convolution Filters in C#
  22. Symmetric Nearest Neighbor in C#
  23. Bump Map Creation Using C#
  24. Normal Map Creation Using C#
  25. Creating Negative Images using C#
  26. Red, Blue, and Green Filters in C#
  27. Converting an Image to ASCII Art in C#
  28. Adjusting Brightness of an Image in C#
  29. Adding Noise to an Image in C#
  30. Adjusting the Gamma of an Image Using C#
  31. Adjusting Contrast of an Image in C#
  32. Drawing a Box With Rounded Corners in C#
  33. Anding Two Images Together Using C#
  34. Motion Detection in C#
  35. Creating Thermometer Chart in C#
  36. Colorizing a Black and White Image in C#
  37. Extracting an Icon From a File
  38. Setting the Pixel Format and Image Format of an Image in .Net
  39. Using Unsafe Code for Faster Image Manipulation
  40. Sobel Edge Detection and Laplace Edge Detection in C#

Converting Image to Black and White in C#

8/29/2008

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

   1: /*
   2: Copyright (c) 2010 <a href="http://www.gutgames.com">James Craig</a>
   3: 
   4: Permission is hereby granted, free of charge, to any person obtaining a copy
   5: of this software and associated documentation files (the "Software"), to deal
   6: in the Software without restriction, including without limitation the rights
   7: to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
   8: copies of the Software, and to permit persons to whom the Software is
   9: furnished to do so, subject to the following conditions:
  10: 
  11: The above copyright notice and this permission notice shall be included in
  12: all copies or substantial portions of the Software.
  13: 
  14: THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15: IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16: FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17: AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18: LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19: OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20: THE SOFTWARE.*/
  21:  
  22: #region Usings
  23: using System.Drawing;
  24: using System.Drawing.Imaging;
  25: #endregion
  26:  
  27: namespace Utilities.Media.Image
  28: {
  29:     /// <summary>
  30:     /// Helper class for setting up and applying a color matrix
  31:     /// </summary>
  32:     public class ColorMatrix
  33:     {
  34:         #region Constructor
  35:  
  36:         /// <summary>
  37:         /// Constructor
  38:         /// </summary>
  39:         public ColorMatrix()
  40:         {
  41:         }
  42:  
  43:         #endregion
  44:  
  45:         #region Properties
  46:  
  47:         /// <summary>
  48:         /// Matrix containing the values of the ColorMatrix
  49:         /// </summary>
  50:         public float[][] Matrix { get; set; }
  51:  
  52:         #endregion
  53:  
  54:         #region Public Functions
  55:  
  56:         /// <summary>
  57:         /// Applies the color matrix
  58:         /// </summary>
  59:         /// <param name="OriginalImage">Image sent in</param>
  60:         /// <returns>An image with the color matrix applied</returns>
  61:         public Bitmap Apply(Bitmap OriginalImage)
  62:         {
  63:             Bitmap NewBitmap = new Bitmap(OriginalImage.Width, OriginalImage.Height);
  64:             using (Graphics NewGraphics = Graphics.FromImage(NewBitmap))
  65:             {
  66:                 System.Drawing.Imaging.ColorMatrix NewColorMatrix = new System.Drawing.Imaging.ColorMatrix(Matrix);
  67:                 using (ImageAttributes Attributes = new ImageAttributes())
  68:                 {
  69:                     Attributes.SetColorMatrix(NewColorMatrix);
  70:                     NewGraphics.DrawImage(OriginalImage,
  71:                         new System.Drawing.Rectangle(0, 0, OriginalImage.Width, OriginalImage.Height),
  72:                         0, 0, OriginalImage.Width, OriginalImage.Height,
  73:                         GraphicsUnit.Pixel,
  74:                         Attributes);
  75:                 }
  76:             }
  77:             return NewBitmap;
  78:         }
  79:  
  80:         #endregion
  81:     }
  82: }

ConvertBlackAndWhite Function

   1: /// <summary>
   2: /// Converts an image to black and white
   3: /// </summary>
   4: /// <param name="Image">Image to change</param>
   5: /// <returns>A bitmap object of the black and white image</returns>
   6: public static Bitmap ConvertBlackAndWhite(Bitmap Image)
   7: {
   8:     ColorMatrix TempMatrix = new ColorMatrix();
   9:     TempMatrix.Matrix = new float[][]{
  10:                     new float[] {.3f, .3f, .3f, 0, 0},
  11:                     new float[] {.59f, .59f, .59f, 0, 0},
  12:                     new float[] {.11f, .11f, .11f, 0, 0},
  13:                     new float[] {0, 0, 0, 1, 0},
  14:                     new float[] {0, 0, 0, 0, 1}
  15:                 };
  16:     return TempMatrix.Apply(Image);
  17: }

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:

   1: float[][] FloatColorMatrix ={ 
   2:         new float[] {1, 0, 0, 0, 0}, 
   3:         new float[] {0, 1, 0, 0, 0}, 
   4:         new float[] {0, 0, 1, 0, 0}, 
   5:         new float[] {0, 0, 0, 1, 0}, 
   6:         new float[] {0, 0, 0, 0, 1} 
   7:     };

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.



Comments

James Craig
October 21, 2010 11:47 AM

Yes, when I say black and white, I mean gray scale.

Ricardo
October 21, 2010 11:02 AM

Isn't that matrix for grayscale transformation?

John
December 18, 2009 9:59 PM

Wonderful contribution! Needed a quick way to make a black-and-white version of an image so I didn't have to call up the designer and this code did exactly what I needed.