Gunnar Peipman's ASP.NET blog

ASP.NET, C#, SharePoint, SQL Server and general software development topics.

Sponsors

News

 
 
 
DZone MVB

Links

Social

How to create grayscale images on .NET

In this example we will use simple color recalculation method to grayscale images. For each pixel on image we will calculate "average color" that we write back on image. Average color is sum of current color's red, green and blue channels integer value divided by three. This value is assigned to all three channels for current pixel.

 

NB! This blog is moved to gunnarpeipman.com

Click here to go to article

Comments

Ramon Smits said:

Or use unsafe code by locking the bitmap object and retrieving the pointer in memory. The colormatrix through gdi is the fastest as this also can be done accellerated.

By the way... you are doing a very rude color to grey conversion. You should weight the color components differently.

# October 24, 2007 4:57 AM

mm said:

how to 8-bit bmp to 8-bit jpg??thanks!

# October 25, 2007 3:33 AM

Jon Hanna said:

There's a problem in not weighting the different colours, since neither the human eye nor display tech works that way. This works well in the example image, but not as well as in others.

Changing

rgb = (int)((c.R + c.G + c.B) / 3);

to:

rgb = (int)(sqrt( 0.241 * c.R * c.R + 0.691 * c.G * c.G + 0.068 * c.B * c.B ));

Will give a much more accurate version, though we can do pretty well much faster with:

rgb = (int)(0.299 * c.R + 0.587 * c.G + 0.114 * c.B);

Perhaps the most commonly seen is the slight rounding of this:

rgb = (int)(0.3 * c.R + 0.59 * c.G + 0.11 * c.B);

Which in practice is going to come out much the same.

# April 6, 2012 4:42 AM