⌘BABAKOV.NET Let's code!
100% [dark] [ru]

Example of Converting a Color Image to Black and White in C#

   There may be many methods for converting a color image to black and white, and possibly even more advanced ones, but for now, the method presented below is the fastest among the ones I know.
   The conversion uses only standard libraries.
   The method's essence is not to work with the image itself, but to work with a block of data. If simplified, it's just freezing the image data in memory, modifying it as needed, and returning it to its original state.

   There's no need to elaborate further, so I'll immediately provide an example of the image conversion procedure with comments:

private void MakeGray(Bitmap bmp)
{
    // Задаём формат Пикселя.
    PixelFormat pxf = PixelFormat.Format24bppRgb;

    // Получаем данные картинки.
    Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
    //Блокируем набор данных изображения в памяти
    BitmapData bmpData = bmp.LockBits(rect, ImageLockMode.ReadWrite, pxf);

    // Получаем адрес первой линии.
    IntPtr ptr = bmpData.Scan0;

    // Задаём массив из Byte и помещаем в него надор данных.
    // int numBytes = bmp.Width * bmp.Height * 3; 
    //На 3 умножаем - поскольку RGB цвет кодируется 3-мя байтами
    //Либо используем вместо Width - Stride
    int numBytes = bmpData.Stride * bmp.Height;
    int widthBytes = bmpData.Stride;
    byte[] rgbValues = new byte[numBytes];

    // Копируем значения в массив.
    Marshal.Copy(ptr, rgbValues, 0, numBytes);

    // Перебираем пикселы по 3 байта на каждый и меняем значения
    for (int counter = 0; counter < rgbValues.Length; counter += 3)
    {
        
        int value = rgbValues[counter] + rgbValues[counter + 1] + rgbValues[counter + 2];
        byte color_b = 0;
     
        color_b = Convert.ToByte(value / 3);


        rgbValues[counter] = color_b;
        rgbValues[counter + 1] = color_b;
        rgbValues[counter + 2] = color_b;

    }
    // Копируем набор данных обратно в изображение
    Marshal.Copy(rgbValues, 0, ptr, numBytes);

    // Разблокируем набор данных изображения в памяти.
    bmp.UnlockBits(bmpData);
}

   The array byte iteration is performed with a step of 3 because each pixel is encoded by 3 bytes R G B.
   In the cycle, the components R G and B are summed up, and the average value of the three components is calculated. Then, instead of the values R G and B, this average value is placed, thus setting the necessary gray tone.

   To work with the procedure, you need to include:
   System.Drawing.Imaging;
   System.Runtime.InteropServices;

Comments (0)

No comments yet.

Leave a comment
Comment
Images (up to 5 MB)
Your comment will appear after moderation.