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 Example   Follow me on Twitter   RSS feed   Donate

This entry was posted in graphics, image processing and tagged , , , , , , , , , . Bookmark the permalink.

1 Response to Use a ColorMatrix to add a watermark to an image in C#

  1. Pingback: Draw a watermark in C# - C# HelperC# Helper

Comments are closed.