SIGN UP MEMBER LOGIN:    
ARTICLE

Create Watermark Text on an Image in ASP.NET

Posted by Ankit Nandekar Articles | ASP.NET Programming May 25, 2011
In this article I will show you how to create watermark text on an image.
Reader Level:
Download Files:
 


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.

Login to add your contents and source code to this article
share this article :
post comment
 

i have tried ravi its working.ok i will check one more time.

Posted by Ankit Nandekar May 25, 2011

i have tried ravi its working.

Posted by Ankit Nandekar May 25, 2011

i am not able to understand the purpose of putting watermark on the image. I run the sample and save the image, however according to you it will not be saved.

Posted by Ravi K Kashyap May 25, 2011
Team Foundation Server Hosting
Become a Sponsor
PREMIUM SPONSORS
  • ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications. Visit DynamicPDF here
    Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Nevron Gauge for SharePoint
Become a Sponsor