[C# Helper]
Index Books FAQ Contact About Rod
[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]

[Beginning Software Engineering]

[C# 5.0 Programmer's Reference]

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

Title: Use a ColorMatrix to add a watermark to an image in C#

[Use a ColorMatrix to add a watermark to an image in C#]

The example Add a watermark to an image in C# explains how to add a translucent watermark to an image. This example does the same thing in a slightly different and probably more efficient way. The example uses the following DrawWatermark method.

// Copy the watermark image over the result image. private void DrawWatermark(Bitmap watermark_bm, Bitmap result_bm, int x, int y) { // Make a ColorMatrix that multiplies // the alpha component by 0.5. ColorMatrix color_matrix = new ColorMatrix(); color_matrix.Matrix33 = 0.5f; // Make an ImageAttributes that uses the ColorMatrix. ImageAttributes image_attributes = new ImageAttributes(); image_attributes.SetColorMatrices(color_matrix, null); // Make pixels that are the same color as the // one in the upper left transparent. watermark_bm.MakeTransparent(watermark_bm.GetPixel(0, 0)); // Draw the image using the ColorMatrix. using (Graphics gr = Graphics.FromImage(result_bm)) { Rectangle rect = new Rectangle(x, y, watermark_bm.Width, watermark_bm.Height); gr.DrawImage(watermark_bm, rect, 0, 0, watermark_bm.Width, watermark_bm.Height, GraphicsUnit.Pixel, image_attributes); } }

The ColorMatrix class contains a matrix of coefficients that are multiplied by the red, green, and blue color components of each pixel in an image. The [3, 3] entry represents a scale factor by which the pixel's alpha component is multiplied.

This example makes a ColorMatrix object with the [3, 3] entry set to 0.5 so it multiplies each pixel's alpha component by 0.5, making it 50% transparent. The program makes an ImageAttributes object that uses the ColorMatrix.

Next the code makes the pixels in the image transparent if they have the same color as the pixel in the upper left corner. It finishes by drawing the watermark image onto the original image while using the ImageAttributes object. That object copies the image at 50% opacity so you get the watermark effect.

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

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