Click here to Skip to main content
15,867,594 members
Articles / Web Development / ASP.NET

How to create image thumbnails (image resizing) on the fly including watermark (text or image)

Rate me:
Please Sign up or sign in to vote.
4.22/5 (14 votes)
12 Dec 2009CPOL2 min read 45.4K   1.9K   72   8
This article describes how you can resize an image at runtime with watermark.

Introduction

This article describes how you can resize an image at runtime, i.e., you don't need to store images of all sizes that you want to display in your web application (like stamp, medium, large etc.). Using this code, you can resize an image to any size as per your needs. You can also make a watermark using text and another image as well.

There are many advantages of using this code, like:

  • No need to store different sizes images as you can resize any image to any size
  • Easy to understand and integrate
  • Supports all browsers
  • Can be used in a page, slide shows, image listing, item listing etc.
  • You can hide the path of the images, so visitors can't get access to them by typing the path into the address bar of the browser

Using the Code

To achieve resizing, please follow these steps: Use the page attached with the article createthumb_image_WM.aspx in your project. Use "createthumb_text_WM.aspx" for text watermarks and "createthumb_image_WM.aspx" for image watermarks.

Just give the file path that you want to re-size, with the target width and height, to the following image resizing function:

C#
private System.Drawing.Bitmap getResizedImage(string psFilePath, 
        int piTargetWidth, int piTargetHeight)
{
    if (File.Exists(psFilePath))
    {
        original_image = new System.Drawing.Bitmap(psFilePath);

        // Calculate the new width and height
        int width = original_image.Width;
        int height = original_image.Height;
        int target_width = Convert.ToInt32(piTargetWidth);
        int target_height = Convert.ToInt32(piTargetHeight);
        int new_width, new_height;

        if (height <= target_height && width <= target_width)
        {
            new_height = height;
            new_width = width;
        }
        else
        {
            float target_ratio = (float)target_width / (float)target_height;
            float image_ratio = (float)width / (float)height;

            if (target_ratio > image_ratio)
            {
                new_height = target_height;
                new_width = (int)Math.Floor(image_ratio * (float)target_height);
            }
            else
            {
                new_height = (int)Math.Floor((float)target_width / image_ratio);
                new_width = target_width;
            }

            new_width = new_width > target_width ? target_width : new_width;
            new_height = new_height > target_height ? target_height : new_height;
        }

        // Create the thumbnail
        final_image = new System.Drawing.Bitmap(new_width, new_height);
        graphic = System.Drawing.Graphics.FromImage(final_image);
        graphic.FillRectangle(new System.Drawing.SolidBrush(
          System.Drawing.Color.Transparent), 
          new System.Drawing.Rectangle(0, 0, target_width, target_height));
        int paste_x = (target_width - new_width) / 2;
        int paste_y = (target_height - new_height) / 2;
        graphic.InterpolationMode = 
          System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; /* new way */
        graphic.DrawImage(original_image, 0, 0, new_width, new_height);
        if (graphic != null) graphic.Dispose();
        if (original_image != null) original_image.Dispose();
        return final_image;
    }
    else
        return null;
}

For example, if you want a 400x400 re-sized image, then you can use the above function like:

C#
System.Drawing.Bitmap imgBGImage = getResizedImage(sFilePath, 400, 400);

You will get the re-sized (400x400) image in the image object, "imgBGImage".

Now, let's see the code for water marking: change the value of the variable "sFilePath" as per your needs, in the following code:

C#
MemoryStream mStream = new MemoryStream();

if (Request.QueryString["_path"] != "")
{
    string sFilePath = "";
    string sWaterMark = "watermark text";
    int x, y;
    
    sFilePath = Server.MapPath("../images/") + Request.QueryString["_path"];

    //resizing the backgroung image
    System.Drawing.Bitmap imgBGImage = getResizedImage(sFilePath, 
      Convert.ToInt32(Request.QueryString["_twidth"]), 
      Convert.ToInt32(Request.QueryString["_theight"]));

    /*drawing water mark text*/
    int startsize = (imgBGImage.Width / sWaterMark.Length);
    //get the font size with respect to length of the string

    //x and y cordinates to draw a string
    x = imgBGImage.Width / 2;
    y = imgBGImage.Height / 2;

    //System.Drawing.StringFormat drawFormat = 
    // new System.Drawing.StringFormat(
    // StringFormatFlags.DirectionVertical); -> draws 
    //          a vertical string for watermark
    System.Drawing.StringFormat drawFormat = 
                new System.Drawing.StringFormat();
    drawFormat.Alignment = StringAlignment.Center;

    drawFormat.FormatFlags = StringFormatFlags.NoWrap;

    //drawing string on Image
    graphic = System.Drawing.Graphics.FromImage(imgBGImage);
    graphic.DrawString(sWaterMark, 
       new Font("Arial", startsize, FontStyle.Regular), 
       new SolidBrush(Color.FromArgb(70, 255, 255, 255)), 
       x, y, drawFormat);
    /*drawing water mark text*/

    //drawing the water mark logo on the backgroung image
    imgBGImage.Save(mStream, System.Drawing.Imaging.ImageFormat.Jpeg);
    Response.Clear();
    Response.ContentType = "image/" + Path.GetExtension(sFilePath);
    Response.BinaryWrite(mStream.GetBuffer());
    if (final_image != null) final_image.Dispose();
    if (imgBGImage != null) imgBGImage.Dispose();
    if (graphic != null) graphic.Dispose();
    if (mStream != null) mStream.Dispose();
    Response.End();

Note: The above code is from the "createthumb_text_WM.aspx" page; please use "createthumb_image_WM.aspx" for image watermarks.

Lastly, use the following HTML code where you want to display the re-sized image:

It contains the following query strings:

  • _path: name of the original image that you want to re-size
  • _twidth: target width of the re-sized image
  • _theight: target height of the re-sized image
HTML
<img src="controller/createthumb_text_WM.aspx?_path=test.jpg&_twidth=200&_theight=200" 
  style="border:none;" alt="Loading..."/>
<p>&nbsp;</p>
<img src="controller/createthumb_image_WM.aspx?_path=toyota6.jpg&_twidth=200&_theight=200" 
  style="border:none;" alt="Loading..."/>
<p>&nbsp;</p>
<img src="controller/createthumb_text_WM.aspx?_path=skoda2.jpg&_twidth=200&_theight=200" 
  style="border:none;" alt="Loading..."/>

As shown in the above code, you just need to pass the the page URL (controller/createthumb_text_WM.aspx) in the src attribute of the image, with the query string that contains the height, width, and image name. And you will get the re-sized image!!!

For example if you want to re-size the image to 200x200, then pass 200 for the query string values for the width and height, and you will get the following output:

demo_200.JPG

Like in the above example, you can give any value for the width and height that you want to re-size to.

This code can also work with slide shows, like:

demo_slide.JPG

Enjoy easy image resizing and watermarking...... :-)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead IndiaNIC Infotech Ltd.
India India
• 3.6 years of experience in IT industry
• 3.6 years of Experience in Web technologies including ASP.net.
• Hands-on experience in Technologies including DotNet 2003/2005 (C# & VB.net) – MVC Framework, MS SQL server 2003/2005/2008, java script, jQuery, Ajax, CSS, SVN, VSS.
• Hands on experience on working in N-Tire Architecture.
• Experience in HTML, DHTML, XML, CSS.
• A quick learner and good management, analytical and database designing skill.
• Experience in Application Servers including IIS 5.0/6.0/7.0

Comments and Discussions

 
QuestionAdd horizontal watermark with outlining Pin
Member 1304079826-Apr-17 21:46
Member 1304079826-Apr-17 21:46 
QuestionSee imageresizing.net instead Pin
Nathanael Jones6-Jan-12 6:36
Nathanael Jones6-Jan-12 6:36 
GeneralGood work Pin
Md. Marufuzzaman13-Dec-09 2:24
professionalMd. Marufuzzaman13-Dec-09 2:24 
GeneralRe: Good work Pin
Prakash Hirani13-Dec-09 17:34
Prakash Hirani13-Dec-09 17:34 
GeneralUnuseful Pin
Laserson12-Dec-09 2:41
Laserson12-Dec-09 2:41 
GeneralThe performance decrease. Pin
Member 293492012-Dec-09 2:09
Member 293492012-Dec-09 2:09 
GeneralRe: The performance decrease. Pin
Prakash Hirani13-Dec-09 17:32
Prakash Hirani13-Dec-09 17:32 
GeneralRe: The performance decrease. Pin
QasimRaza12-Jan-11 0:26
QasimRaza12-Jan-11 0:26 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.