Serge's World

Blogging about software development, astronomy, genealogy and more.

Image Processing in C#: Part 12 - Decreasing the Colour Depth

Decreasing the colour depth involves converting colour values to standard values.

Specifying an offset, preferably a value evenly divisible into 256, such as 16, 24 or 32, we then need to make sure that the red, green and blue components’ values get rounded off to multiples of this offset.

For example, using an offset of 16, value colour values would be 0, 15, 31, 47,……, 255. and all values would need to be rounded off to these values for each of the colour components.

To be able to do this, we take the component value, and then add half of the offset to the value. We then subtract the modulo of this value and the offset. This then gives values along the lines of 0, 16, 32, …., 256, so we will need to subtract 1 from this, but will need to put in a correction for 0, since that value needs to remain as it is.

Decrease colour depth

public void ApplyDecreaseColourDepth(int offset)
{
    int A, R, G, B;
    Color pixelColor;

    for (int y = 0; y < bitmapImage.Height; y++)
    {
        for (int x = 0; x < bitmapImage.Width; x++)
        {
            pixelColor = bitmapImage.GetPixel(x, y);
            A = pixelColor.A;
            R = ((pixelColor.R + (offset / 2)) - ((pixelColor.R + (offset / 2)) % offset) - 1);
            if (R < 0)
            {
                R = 0;
            }
            G = ((pixelColor.G + (offset / 2)) - ((pixelColor.G + (offset / 2)) % offset) - 1);
            if (G < 0)
            {
                G = 0;
            }
            B = ((pixelColor.B + (offset / 2)) - ((pixelColor.B + (offset / 2)) % offset) - 1);
            if (B < 0)
            {
                B = 0;
            }
            bitmapImage.SetPixel(x, y, Color.FromArgb(A, R, G, B));
        }
    }

}

The full source used in the series is available from https://github.com/sjmeunier/image-processor.

Originally posted on my old blog, Smoky Cogs, on 19 Nov 2009

Tag Cloud

Algorithms (3) Android (10) Astronomy (25) Audio (1) Audiobooks (1) Barcodes (9) C# (69) Css (1) Deep sky (6) Esoteric languages (3) Family (3) Fractals (10) Gaming (1) Genealogy (14) General (2) Geodesy (3) Google (1) Graphics (3) Hubble (2) Humour (1) Image processing (23) Java (8) Javascript (5) jQuery (3) Jupiter (3) Maths (22) Moon (5) Music (4) Pets (5) Programming (88) Saturn (1) Science (1) Spitzer (4) Sun (4) Tutorials (68) Unity (3) Web (9) Whisky (13) Windows (1) Xamarin (2)