Create Watermark Text on an Image in ASP.NET



If you want to protect your images from being reused by others, then the best way to do that is with watermark text on the images.

In my article I will show you how to create watermark text on an image.

Follow these simple steps:

Step 1:

Create an Images Folder for images in your website.

Step 2:

Drag an image for which you want to create a watermark onto the web page; the web page looks like:

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
</
head>
<
body>
<
form id="form1" runat="server">
<div>
<
img src="Images/nature_wallpaper7.jpg" style="height: 498px; width: 594px" />
</div>
</
form>
</
body>
</html>

Step 3:

Create a class i.e. a WaterMark in the appcode folder; to do that right-click on the Appcode folder then click on Add Items; select class give it the name WaterMark.

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net.Mime;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;

/// <summary>
///
Summary description for ImageHandler
/// </summary>
public class WaterMark : IHttpHandler
{
 
    public string GetContentType(String path)
    {
        switch (Path.GetExtension(path))
        {
            case ".bmp": return "Image/bmp";
            case ".gif": return "Image/gif";
            case ".jpg": return "Image/jpeg";
            case ".png": return "Image/png";
            default: break;
        }
        return String.Empty;
    }

    public ImageFormat GetImageFormat(String path)
    {
        switch (Path.GetExtension(path).ToLower())
        {
            case ".bmp": return ImageFormat.Bmp;
            case ".gif": return ImageFormat.Gif;
            case ".jpg": return ImageFormat.Jpeg;
            case ".png": return ImageFormat.Png;
            default: return null;
        }
    }

    protected byte[] WatermarkImage(HttpContext context)
    {

        byte[] imageBytes = null;
        if (File.Exists(context.Request.PhysicalPath))
        {
            // This is the Name which will appear as a watermark on image.
            string watermark = "http://www.ankitnandekar.wordpress.com";

            Image image = Image.FromFile(context.Request.PhysicalPath);

            Graphics graphic;
            if (image.PixelFormat != PixelFormat.Indexed && image.PixelFormat != PixelFormat.Format8bppIndexed && image.PixelFormat != PixelFormat.Format4bppIndexed && image.PixelFormat != PixelFormat.Format1bppIndexed)
            {
 
                graphic = Graphics.FromImage(image);
            }
            else
            {
 
                Bitmap indexedImage = new Bitmap(image);
                graphic = Graphics.FromImage(indexedImage);

                // Draw the contents of the original bitmap onto the new bitmap.
                graphic.DrawImage(image, 0, 0, image.Width, image.Height);
                image = indexedImage;
            }
            graphic.SmoothingMode = SmoothingMode.AntiAlias & SmoothingMode.HighQuality;
//This is the font for your watermark

            Font myFont = new Font("Arial", 40);
            SolidBrush brush = new SolidBrush(Color.FromArgb(220, Color.Beige));

            //This gets the size of the graphic

            SizeF textSize = graphic.MeasureString(watermark, myFont);

            // Code for writing text on the image and showing its postion on images.

            PointF pointF = new PointF(750, 1100);
            graphic.DrawString(watermark, myFont, brush, pointF);

            using (MemoryStream memoryStream = new MemoryStream())
            {
                image.Save(memoryStream, GetImageFormat(context.Request.PhysicalPath));
                imageBytes = memoryStream.ToArray();
            }
        }
        return imageBytes;
    }

    #region IHttpHandler Members

    public bool IsReusable
    {
        get { return false; }
    }

    public void ProcessRequest(HttpContext context)
    {
        context.Response.Clear();
        context.Response.ContentType = GetContentType(context.Request.PhysicalPath);
        byte[] imageBytes = WatermarkImage(context);
        if (imageBytes != null)
        {
            context.Response.OutputStream.Write(imageBytes, 0, imageBytes.Length);
        }
        else
        {

            context.Response.StatusCode = 404;
        }
        context.Response.End();
    }

    #endregion
}

Step 4:

In the Webconfig file add the following line between <httpHandlers></httpHandlers> tag. So it will look like:

<httpHandlers>
<add verb="*" path="*.jpg,*.gif" type="WaterMark" />
</httpHandlers>

Step 5:

Run the Website and see the watermark on the image.