Click here to Skip to main content
15,887,945 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
In this code example:

C#
public void convertBmp(string imagepath)
{
    Bitmap image = new Bitmap(imagepath);

    for (int y = 0; y < image.Height; y++)
    {
        for (int x = 0; x < image.Width; x++)
        {
            Color c = image.GetPixel(x, y);
            int luma = (int)(c.R * 0.3 + c.G * 0.59 + c.B * 0.11);
            image.SetPixel(x, y, Color.FromArgb(luma, luma, luma));
        }
    }

    image.Save("C:\\test.bmp", System.Drawing.Imaging.ImageFormat.Bmp);
 }


It will convert a bitmap file to 'grayscale'. When you open the resulting 'test.bmp' file in MS Paint, for example, it identifies it as a '24-bit Bitmap" file. What I need is the ability to save a .bmp file as a "Monochromatic Bitmap" file. Note that "Monochromatic" is the key word here - not "b+w" or "grayscale", but that specific bmp type. I was hoping I could stumble onto a System.Drawing.Imaging.ImageFormat.MonochromaticBmp image format, but no dice. Help!
Posted
Updated 5-Oct-11 15:09pm
v2
Comments
Sergey Alexandrovich Kryukov 5-Oct-11 21:01pm    
A problem is simple, but... tag it! Your platform, language, UI library. Don't tell us "it's apparent from the source code", just tag it all.
--SA

1 solution

Oh! First of all, forget about GetPixel/SetPixel and never recall it again. :-) The performance is not acceptable. Instead, use System.Drawing.Bitmap.LockBits. You will find a code sample here: http://msdn.microsoft.com/en-us/library/5ey6h79d.aspx[^].

You will need two bitmaps as your target bitmap should be of different pixel format on output, such as System.Drawing.Imaging.System.Drawing.Imaging.Format16bppGrayScale, see http://msdn.microsoft.com/en-us/library/system.drawing.imaging.pixelformat.aspx[^].
If you simply remove saturation from your bit data and save it in the same format, you will waste memory and disk space on color bitmap while not actually using colors.

Now, grayscale. Those good photographers working with computers know that there are many different ways to make good grayscale. Instead of just setting color saturation to zero, they select one channel, run different filters and creatively combine those transformation in order to emphasize one or another part of dynamic range. You can do it, too.

You can use some simplest method though. Look at this article:
http://www.bobpowell.net/grayscale.htm[^].

For goodness sake, ignore the first code sample using those stupid GetPixel/SetPixel methods. Instead, use the method in the section "Alternative Version using the ColorMatrix class". This is probably the fastest way.

—SA
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900