Anding Two Images Together Using C#

Combining images together.
May 27 2009 by James Craig

So first I'm stuck working on SharePoint site management (which I'm going to be doing for a little while) and then I become sick with something that seems to be taking out everyone around here. However I'm now back doing some coding (in my spare time anyway). And since my update to the ORM isn't ready yet, I'm going to hand out some more image manipulation code.
Today I'm going to show you how to and two images together. And, Or, Xor, etc. are logical operations that, as programmers, you've seen about 10,000 times. They can also be used in image processing, causing various effects. All of them are extremely simple, so let's look at the basic code:

 /// <summary>
/// ands two images
/// </summary>
/// <param name="Image1">Image to manipulate</param>
/// <param name="Image2">Image to manipulate</param>
/// <returns>A bitmap image</returns>
public static Bitmap And(Bitmap Image1, Bitmap Image2)
Bitmap NewBitmap = new Bitmap(Image1.Width, Image1.Height);
BitmapData NewData = Image.LockImage(NewBitmap);
BitmapData OldData1 = Image.LockImage(Image1);
BitmapData OldData2 = Image.LockImage(Image2);
int NewPixelSize = Image.GetPixelSize(NewData);
int OldPixelSize1 = Image.GetPixelSize(OldData1);
int OldPixelSize2 = Image.GetPixelSize(OldData2);
for (int x = 0; x < NewBitmap.Width; ++x)
for (int y = 0; y < NewBitmap.Height; ++y)
Color Pixel1 = Image.GetPixel(OldData1, x, y, OldPixelSize1);
Color Pixel2 = Image.GetPixel(OldData2, x, y, OldPixelSize2);
Image.SetPixel(NewData, x, y,
Color.FromArgb(Pixel1.R & Pixel2.R,
Pixel1.G & Pixel2.G,
Pixel1.B & Pixel2.B),
Image.UnlockImage(NewBitmap, NewData);
Image.UnlockImage(Image1, OldData1);
Image.UnlockImage(Image2, OldData2);
return NewBitmap;

The code above uses a couple of functions from my utility library, specifically Image.LockImage, UnlockImage, etc. Most of which can be removed or replaced with GetPixel/SetPixel functions. As you can see, all that it takes in is two images (and it makes the assumption that they're the same size). It then just does a logical and of the red, green, and blue values for the two pixels. You can easily substitute a ^ or a | instead of the &. That's all there is to it really. So try it out, leave feedback, and happy coding.