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.
// Copy the watermark image over the result image.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 ImageAttribute that uses the ColorMatrix, and then uses the ImageAttribute to redraw the image 50% transparent.
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);
}
}



Comments