Watermarking Image

Description: Watermarks images by placing a semi-transparent image over the top of an existing image at the specified x,y coordinates and with the specified opacity (on a scale between 0 and 100).
Tested Platform: .NET 4.0, Visual Studio 2010, Windows 7
Language: C#
private Image Watermark(ref Image wourceImage, ref Image watermarkImage, int x, int y, int opacity = 30) {
    Bitmap srcImage = new Bitmap(sourceImage);
    Bitmap wtrImage = new Bitmap(watermarkImage);

    if (opacity < 0) { opacity = 0; }
    if (opacity > 100) { opacity = 100; }

    float opaque = (opacity / 100.0f);

    using (Graphics g = Graphics.FromImage(srcImage)) {
        System.Drawing.Imaging.ColorMatrix matrix = new System.Drawing.Imaging.ColorMatrix(
            new float[][] 
            {
                new float[] {1, 0, 0, 0, 0},
                new float[] {0, 1, 0, 0, 0},
                new float[] {0, 0, 1, 0, 0},
                new float[] {0, 0, 0, opaque, 0},
                new float[] {0, 0, 0, 0, 1}
            });

        System.Drawing.Imaging.ImageAttributes attributes = new System.Drawing.Imaging.ImageAttributes();
        attributes.SetColorMatrix(matrix);

        g.DrawImage(wtrImage, new Rectangle(x, y, wtrImage.Width, wtrImage.Height), 0, 0, wtrImage.Width, wtrImage.Height, GraphicsUnit.Pixel, attributes);
    }

    return (Image)srcImage;
}

Submitted: October 23, 2012

Return to the snippets listing