Thursday, August 18, 2011

Digital Image Processing - Image Watermarking in C# and Asp.net

In Today's internet world we see many images, photos, backgrounds etc. we can easily copy and paste them. But we don't know the actual creator of this images.

In this post i am not talking about SharePoint, it's all about C# coding. Just wanted to memorize the old things.

So lets do it....

Image Watermarking - Digital watermarking is the process of embedding information into a digital signal which may be used to verify its authenticity or the identity of its owners, in the same manner as paper bearing a watermark for visible identification. (Thank you wikipedia for this definition.)

I have created a web application that will demonstrate how to create a watermarked image with Text and Logo.

1. Create a Web Application Project in Visual Studio

2.Create layout in Aspx page.

3. Create function called GenerateWatermarkedImage()  and add following code in it.

Web.config file AppSettings
<appSettings >
    <add key="WatermarkImagePath" value="\Images\watermark.gif"/>
    <add key="SampleImagePath" value="\Images\SampleImage.jpg"/>
    <add key="TragetImagePath" value="\Images\TragetImage.jpg"/>
</appSettings>

Namespaces used
using System;
using System.Configuration;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Web;

GenerateWatermarkedImage() Function
public void GenerateWatermarkedImage()
{
            // Load Source Image
            String strSourceImagePath = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["SourceImagePath"]);
            Image imgSource = Image.FromFile(strSourceImagePath);

            //Create New Bitmap Image
            int socWidth = imgSource.Width;
            int socHeight = imgSource.Height;
            Bitmap bmPhoto = new Bitmap(socWidth, socHeight, PixelFormat.Format24bppRgb);
            bmPhoto.SetResolution(72, 72);
            Graphics grPhoto = Graphics.FromImage(bmPhoto);

            //Load Logo Image
            String strLogoImagePath = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["LogoImagePath"]);
            Image imgLogo = new Bitmap(strLogoImagePath);
            int logoWidth = imgLogo.Width;
            int logoHeight = imgLogo.Height;

            //#####################################
            //Step #1 - Watermark Text
            grPhoto.SmoothingMode = SmoothingMode.AntiAlias;
            grPhoto.DrawImage(
                imgSource,
                new Rectangle(0, 0, socWidth, socHeight),
                0,
                0,
                socWidth,
                socHeight,
                GraphicsUnit.Pixel);

            //Determine the largest possible size for WaterMark Text Message
            int[] sizes = new int[] { 16, 14, 12, 10, 8, 6, 4 };
            Font crFont = null;
            SizeF crSize = new SizeF();
            string strWaterMarkText = TxtWatermark.Text;
            for (int i = 0; i < 7; i++)
            {
                crFont = new Font("arial", sizes[i], FontStyle.Bold);
                crSize = grPhoto.MeasureString(strWaterMarkText, crFont);

                if ((ushort)crSize.Width < (ushort)socWidth)
                    break;
            }

            //String Alignment to Center
            int yPixlesFromBottom = (int)(socHeight * .05);
            float yPosFromBottom = ((socHeight -
                       yPixlesFromBottom) - (crSize.Height / 2));
            float xCenterOfImg = (socWidth / 2);

            StringFormat StrFormat = new StringFormat();
            StrFormat.Alignment = StringAlignment.Center;

            //Draw the WaterMark string at the appropriate position
            SolidBrush semiTransBrush2 = new SolidBrush(Color.FromArgb(153, 0, 0, 0));

            grPhoto.DrawString(
                strWaterMarkText,
                crFont,
                semiTransBrush2,
                new PointF(xCenterOfImg + 1, yPosFromBottom + 1),
                StrFormat);

            SolidBrush semiTransBrush = new SolidBrush(Color.FromArgb(153, 255, 255, 255));

            grPhoto.DrawString(
                strWaterMarkText,
                crFont,
                semiTransBrush,
                new PointF(xCenterOfImg, yPosFromBottom),
                StrFormat);

            //#####################################
            //Step #2 - Watermark Logo
            Bitmap bmWatermark = new Bitmap(bmPhoto);
            bmWatermark.SetResolution(imgSource.HorizontalResolution, imgSource.VerticalResolution);

            Graphics grWatermark = Graphics.FromImage(bmWatermark);

            //Translucent watermark
            ImageAttributes imageAttributes = new ImageAttributes();
            ColorMap colorMap = new ColorMap();

            colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
            colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
            ColorMap[] remapTable = { colorMap };

            imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);

            //Change the opacity of the watermark
            float[][] colorMatrixElements = {
                        new float[] {1.0f,  0.0f,  0.0f,  0.0f, 0.0f},
                        new float[] {0.0f,  1.0f,  0.0f,  0.0f, 0.0f},
                        new float[] {0.0f,  0.0f,  1.0f,  0.0f, 0.0f},
                        new float[] {0.0f,  0.0f,  0.0f,  0.3f, 0.0f},
                        new float[] {0.0f,  0.0f,  0.0f,  0.0f, 1.0f}
                                                };
            ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements);
            imageAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);

            //Draw the watermark
            int xPosOfWm = ((socWidth - logoWidth) - 10);
            int yPosOfWm = 10;

            grWatermark.DrawImage(imgLogo,
                new Rectangle(xPosOfWm, yPosOfWm, logoWidth,
                                                 logoHeight),
                0,
                0,
                logoWidth,
                logoHeight,
                GraphicsUnit.Pixel,
                imageAttributes);

            //Replace the original Image with the new Bitmap
            imgSource = bmWatermark;
            grPhoto.Dispose();
            grWatermark.Dispose();

            //Save Watermarked Image
            String TragetImagePath = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["TragetImagePath"]);
            imgSource.Save(TragetImagePath);
            imgSource.Dispose();
            imgLogo.Dispose();

            ImgWatermarked.ImageUrl = ConfigurationManager.AppSettings["TragetImagePath"];
}

4. Watermarked Image


2 comments:

  1. errer in this last line ........
    ImgWatermarked.ImageUrl = ConfigurationManager.AppSettings["TragetImagePath"];

    ReplyDelete
    Replies
    1. This can be a configuration error, please check you AppSettings and image url (Url should be Relative Path)

      Delete