How to grayout an image in .Net
Posted by Dan Rigsby on March 28th, 2008
Here is a handy method for making a grayscale version of an image. I use this method a lot to grayout icons that I wish to show as disabled. All you need to do is pass in the image and it will apply a grayscale over it. The key to getting all of this to work is the ColorMatrix. There is a detailed article about how this works on codeproject: http://www.codeproject.com/KB/GDI-plus/colormatrix.aspx.
public static void ApplyGrayscale( ref Image image) { // Build color matrix set at 1/3 ColorMatrix matrix = new ColorMatrix(); matrix[0, 0] = 1/3f; matrix[0, 1] = 1/3f; matrix[0, 2] = 1/3f; matrix[1, 0] = 1/3f; matrix[1, 1] = 1/3f; matrix[1, 2] = 1/3f; matrix[2, 0] = 1/3f; matrix[2, 1] = 1/3f; matrix[2, 2] = 1/3f; // Create image attributes that will applied to the image ImageAttributes attributes = new ImageAttributes(); attributes.SetColorMatrix(matrix); Graphics g = null; try { // Get the graphics object from the image g = Graphics.FromImage(image); // Redraw the image on the graphics object using the grayscale color matrix g.DrawImage(image, new Rectangle(0, 0, image.Width, image.Height), 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, attributes); } finally { if (g != null) { g.Dispose(); } } }
Here are some sample before and after images (of my daughter Claire):
Here is another example with a more typical line-of-business image:
To make this easier to try out or use, I have wrapped the method into a executable as well. You can download the source for this here: http://www.danrigsby.com/Files/Rigsby.ImageUtilities.Grayscale.zip
To run the program, compile the code and execute the exe file while passing in the source file name and the file name you want to save the new grayscaled image to, like this:
Rigsby.ImageUtilities.Grayscale.exe "c:\Claire.jpg" "c:\Claire-Gray.jpg"











March 28th, 2008 at 11:35 pm
Nice! Sounds like a helpful class to add to our common framework. Now, where to put it since it depends on System.Drawing…
March 29th, 2008 at 7:32 am
We have this in an ININ.Resources.dll file atm. System.Drawing is pretty standard. I would guess this could go into ININ.Common.dll without any issues. It would be good for web or windows clients.
March 30th, 2008 at 4:05 pm
[...] How to Grayout an Image in .NET (Dan Rigsby) [...]
March 31st, 2008 at 8:35 pm
“ht” missing from Link
April 1st, 2008 at 12:01 am
[...] Dan Rigsby demonstrates a technique to grayout an image in .Net. [...]
April 1st, 2008 at 7:29 am
For a more human friendly grayscale conversion use: 30% of the red value, 59% of the green value, and 11% of the blue value (Wikipedia).
April 1st, 2008 at 5:23 pm
Great function! Another one to try is the .NET built-in function in System.Windows.Forms:
ControlPaint.DrawImageDisabled
April 2nd, 2008 at 7:36 am
[...] Dan Rigsby » How to grayout an image in .Net (tags: .net graphics) [...]
April 7th, 2008 at 1:56 pm
[...] How to grayout an image in .Net [...]