Creating Negative Images using C#

Negative effect in images.
May 29 2009 by James Craig

This is another image processing post. In this post, I'm going to show you some basic code to create negative images. Generally speaking a negative image isn't that useful. However it does have the ability to help show differences within the image and plus it just looks cool. Basically what we're doing is a logical not (just flipping some bits). So if this were a 1bit image we'd just be flipping the 1s to 0s and 0s to 1s. However no one uses a 1bit image and instead we're using 24/32bit images (or 16 or 48 or 8...). So let's see what we need to do:

 /// <summary>
/// gets the negative of the image
/// </summary>
/// <param name="OriginalImage">Image to manipulate</param>
/// <returns>A bitmap image</returns>
public static Bitmap Negative(Bitmap OriginalImage)
{
Bitmap NewBitmap = new Bitmap(OriginalImage.Width, OriginalImage.Height);
BitmapData NewData = Image.LockImage(NewBitmap);
BitmapData OldData = Image.LockImage(OriginalImage);
int NewPixelSize = Image.GetPixelSize(NewData);
int OldPixelSize = Image.GetPixelSize(OldData);
for (int x = 0; x < NewBitmap.Width; ++x)
{
for (int y = 0; y < NewBitmap.Height; ++y)
{
Color CurrentPixel = Image.GetPixel(OldData, x, y, OldPixelSize);
Color TempValue = Color.FromArgb(255 - CurrentPixel.R, 255 - CurrentPixel.G, 255 - CurrentPixel.B);
Image.SetPixel(NewData, x, y, TempValue, NewPixelSize);
}
}
Image.UnlockImage(NewBitmap, NewData);
Image.UnlockImage(OriginalImage, OldData);
return NewBitmap;
}

The code above uses a couple of functions from my utility library, specifically the Image.LockImage, UnlockImage, etc. functions. These functions are there to speed up things but can be removed/replaced with GetPixel/SetPixel functions that are built in to .Net. Anyway, if you look at the loop, all we're doing is taking the current pixel value and subtracting that from 255 for red, green, and blue values. So instead of just flipping bits we need to subtract the current pixel value from 255. That's all there is to it really. Anyway, I hope this helps you out. Give it a try, leave feedback, and happy coding.