Serge's World

Blogging about software development, astronomy, genealogy and more.

Image Processing in C#: Part 1 - Inverting an image

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. The full source used in the series is available from https://github.com/sjmeunier/image-processor.

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.

Inverted 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 source). 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));
        }
    }

}

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)