This is the first part of my series on image processing, and to start off with, I will cover a relatively easy topic – how to invert the colours of an image.

You can download the full code for the sample application which contains code for all the image effects covered in the series here.

Actually inverting the colours of an image – in essence, creating a negative of the image, is remarkably easy. All it entails is getting the colour of each pixel, which is broken down into red, green and blue and then subtracting each component from 255.

The Bitmap object we are using in C# uses colour components in the range of 0-255, hence why we subtract the value from 255.

There is also an Alpha component to a colour, but we ignore that and just reuse the original value.

Once we have adjusted the colour components, we set the pixel to the new colour.

Inverting an image

Inverting an image


The code below does not include the instantiation of the bitmapData variable, since the function below forms part of a larger class (available in the full download). It is a standard Bitmap object.

public void ApplyInvert()
{
    byte 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 = (byte)(255 - pixelColor.R);
            G = (byte)(255 - pixelColor.G);
            B = (byte)(255 - pixelColor.B);
            bitmapImage.SetPixel(x, y, Color.FromArgb((int)A, (int)R, (int)G, (int)B));
        }
    }

}
Share