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/Bookmark

Related posts:

  1. Image Processing in C#: Colour filters Implementing a colour filter is a rather simple affair. All...
  2. Image Processing in C#: Converting an image to greyscale Converting an image to greyscale is a relatively easy effect...
  3. Image Processing in C#: Adjusting the gamma Gamma correction has a history based on the properties of...
  4. Image Processing in C#: Decreasing the colour depth Decreasing the colour depth involves converting colour values to standard...
  5. Image Processing in C#: Adjusting the brightness To increase the brightness of an image, all you need...

Related posts brought to you by Yet Another Related Posts Plugin.