[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Use a mask to overlay parts of one picture on another in C#

[Use a mask to overlay parts of one picture on another in C#]

This example lets you overlay one picture on top of another but only copying pixels where a separate mask image is black. In the picture, for example, the program draws the overlay image on the main image. It only copies pixels where the mask image is black, so it only copies the colored strawberries onto the final result.

The key piece of this example is the following OverlayWithMask function.

private Bitmap OverlayWithMask(Bitmap main_image, Bitmap overlay_image, Bitmap mask_image) { if (main_image == null || overlay_image == null || mask_image == null) return null; result_image = new Bitmap(main_image); Bitmap32 bm32_main = new Bitmap32(main_image); Bitmap32 bm32_overlay = new Bitmap32(overlay_image); Bitmap32 bm32_mask = new Bitmap32(mask_image); Bitmap32 bm32_result = new Bitmap32(result_image); bm32_main.LockBitmap(); bm32_overlay.LockBitmap(); bm32_mask.LockBitmap(); bm32_result.LockBitmap(); for (int y = 0; y < bm32_main.Height; y++) { for (int x = 0; x < bm32_main.Width; x++) { byte r, g, b, a; bm32_mask.GetPixel(x, y, out r, out g, out b, out a); if (r == 0 && g == 0 && b == 0) { bm32_overlay.GetPixel(x, y, out r, out g, out b, out a); bm32_result.SetPixel(x, y, r, g, b, a); } } } bm32_main.UnlockBitmap(); bm32_overlay.UnlockBitmap(); bm32_mask.UnlockBitmap(); bm32_result.UnlockBitmap(); return result_image; }

This function verifies that the three input images are not null. It then initializes a result bitmap to a copy of the main input image.

Next, the code creates Bitmap32 objects to represent the four images (three input images and one result image) so it can work with their pixels more quickly. It then loops through the images' pixels. (For information about the Bitmap32 class, see Use the Bitmap32 class to manipulate image pixels very quickly in C#.

For each pixel, the code gets the mask image's red, green, and blue color components. If those are all zero, the code sets the result image's pixel to the corresponding pixel in the overlay image. If any of the color components is not zero, the function leaves the output pixel alone.

After it has processed all of the pixels, the function unlocks the Bitmap32 objects and returns the result image.

Download the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.