Click here to Skip to main content
Click here to Skip to main content
Go to top

Playing with Images in ASP.NET

, 14 Jan 2013
Rate this:
Please Sign up or sign in to vote.
Some tips for working with images in ASP.NET using C#.

Introduction

Hello friends, in this article we are going to learn two things related to images and file upload control. This article is for complete beginners who are working with File Upload control and images and do not know much about the below mentioned points. I have divided this article into three sections:

  1. Finding the height and width of an image.
  2. Appending a time stamp with the image name while saving it.
  3. Adding a watermark on an image while uploading it.

First, before looking at the code, this is how my sample page looks like...

Image of my sample application

Explanation

  1. Finding the height and width of an image – Sometimes in our applications we allow our users to upload their images. And in some cases we want them to upload an image of a specific dimension. For example – 450x900. Below is the code for finding the height and width.
  2. Code to check the height and width of an image – Default.aspx page code

    <%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" 
             AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
    <asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
    </asp:Content>
    <asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
        <h2>
            Welcome to ASP.NET!
        </h2>
        <p>
            Please Select an Image file:    
            <asp:FileUpload ID="FUP_WatermarkImage" runat="server" />
        </p>
        <p>
            <asp:Button ID="btnUpload" runat="server" Text="Upload Image" onclick="btnUpload_Click" />
        </p>
        <p>
            <asp:Image ID="imgUploadedImage" runat="server" Width="250" 
                   Height="250" BorderColor="Black" BorderStyle="Solid" BorderWidth="1" />
        </p>
    </asp:Content>

    Note – Please note that in the ASP.NET Image control I have kept the width and height as 250 for both. So in my code I am going to check the images whether its height and width exceeds 250*250 dimension. If it exceeds, then I’ll show an error message to the user and won’t allow him to upload the image.

    protected void btnUpload_Click(object sender, EventArgs e)
    {
        if (Fupload_WatermarkImage.HasFile)
        {
            string FileType = Path.GetExtension(Fupload_WatermarkImage.PostedFile.FileName).ToLower().Trim();
            // Checking the format of the uploaded file.
            if (FileType != ".jpg" && FileType != ".png" && FileType != ".gif" && FileType != ".bmp")
            {
                string alert = "alert('File Format Not Supported. Only .jpg, .png, .bmp and .gif file formats are allowed.');";
                ScriptManager.RegisterStartupScript(this, GetType(), "JScript", alert, true);
            }
            else
            {
                // Getting the stream of the selected image and assign it to the Image Object.
                System.Drawing.Image UploadedImage = System.Drawing.Image.FromStream(Fupload_WatermarkImage.PostedFile.InputStream);
                // Checking if the Width or height is greater than 250px
                if (UploadedImage.PhysicalDimension.Width > 250 || UploadedImage.PhysicalDimension.Height > 250)
                {
                    string alert = "alert('Image size should be exactly 250*250 dimension. Your Current Image width is " + 
                      UploadedImage.PhysicalDimension.Width + " and height is " + 
                      UploadedImage.PhysicalDimension.Height + ".');";
                    ScriptManager.RegisterStartupScript(this, GetType(), "JScript", alert, true);
                }
                else
                {
                    // SOME CODE COMES HERE...
                }
            }
        }
    }

    User tries to upload image with a dimension of more than 250 pixels

    Image indicating the width of the uploaded image–

    Image indicating the height of the uploaded image–

    Error message shown to the user

  3. Appending a time stamp with the image name while saving it – Sometimes a user might add an image with the same name twice. In that case if you want to differentiate between the images, then you can attach the current timestamp with the image name. Below is the code for doing the same.
  4. // Getting the file name of the selected image
    string FileName = Path.GetFileNameWithoutExtension(Fupload_WatermarkImage.PostedFile.FileName);
    // Getting the file extension of the selected image
    string FileExtension = Path.GetExtension(Fupload_WatermarkImage.PostedFile.FileName);
    // Creating a complete relative path for storing the image.
    // And also attaching the datetime stamp with the image name.
    string path = "Watermarked Images/" + FileName + 
           DateTime.Now.ToString("yyyy-MM-dd HHmmtt") + FileExtension;
                        
    // Saving the Image.
    Fupload_WatermarkImage.SaveAs(Server.MapPath(path));
                        
    // Assigning the uploaded image url to the Image control.
    imgUploadedImage.ImageUrl = path;
    if (!String.IsNullOrEmpty(imgUploadedImage.ImageUrl))
    {
        // Showing a notification of success after uploading.
        string alert = "alert('Image uploaded successfully');";
        ScriptManager.RegisterStartupScript(this, GetType(), "JScript", alert, true);
    }

    Note – You can easily understand the code since I have added the appropriate comments with each line of my code. The line of code marked in yellow is where I am attaching my current time stamp with the image name. Below is the image which shows how exactly the image is saved.

    Selected an image with height and width less than 250 pixels

    Code debugged

    The current time is attached with the image name. So the next time even if I upload an image with the same name, I can still upload it since the timestamp differentiates it.

    Final output – Image being displayed in the Image control

    Image uploaded in the folder–

  5. Watermarking an image – Sometimes when we add images from our application, we do not want other users to copy it or use it in their applications. Watermarking is the option which helps protect our images from getting copied or used by other users. Below is the code written to add watermark on an image before saving it in a folder.
  6. Code for watermarking – Content marked in yellow actually writes / watermarks the image.

    // Create an Image Object and fill it with the stream of the selected image.
    System.Drawing.Image image = 
      System.Drawing.Image.FromStream(Fupload_WatermarkImage.PostedFile.InputStream);
                        
    // Get the height and width of an image.
    int width = image.Width;
    int height = image.Height;
    // Creating the Bitmap Object and assigning the width and height of the image.
    // It internally creates a graphical image with the same dimension.
    System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(width, height);
                        
    // Creating a Graphics Object from the Bitmap Object.
    System.Drawing.Graphics graphics1 = System.Drawing.Graphics.FromImage((System.Drawing.Image)bmp);
                        
    // Assigning few properties to the Graphics Object, to maintain the quality of the image.
    graphics1.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
    graphics1.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
    graphics1.Clear(System.Drawing.Color.Transparent);
    graphics1.DrawImage(image, 0, 0, width, height);
    // Create the Font and the Brush Object and assign appropriate parameters inorder to add watermark to the image.
    System.Drawing.Font font = new System.Drawing.Font("Arial", 20);
    System.Drawing.SolidBrush brush = new System.Drawing.SolidBrush(System.Drawing.Color.Aqua);
    // Drawstring actually writes / watermarks the image with the specified content.
    // Parameters contain :- Watermark Content, font style, brush used, x and y position for the string to be written
    graphics1.DrawString("C Sharp Corner", font, brush, 25F, 115F); 
                        
    // Create the image object from the bitmap and then use it to save the watermarked image in the folder.
    System.Drawing.Image newImage = (System.Drawing.Image)bmp;
    // Getting the file name of the selected image
    string FileName = Path.GetFileNameWithoutExtension(Fupload_WatermarkImage.PostedFile.FileName);
    // Getting the file extension of the selected image
    string FileExtension = Path.GetExtension(Fupload_WatermarkImage.PostedFile.FileName);
    // Creating a complete relative path for storing the image. And also attaching the datetime stamp with the image name.
    string path = "Watermarked Images/" + FileName + DateTime.Now.ToString("yyyy-MM-dd HHmmtt") + FileExtension;
    // Saving the Watermarked Image in the specified folder
    newImage.Save(Server.MapPath(path));
    // Assigning the uploaded image url to the Image control.
    imgUploadedImage.ImageUrl = path;
    // Disposing the Graphics Object and other resources from the memory.
    graphics1.Dispose();
    if (!String.IsNullOrEmpty(imgUploadedImage.ImageUrl))
    {
        // Showing a notification of success after uploading.
        string alert = "alert('Image uploaded successfully');";
        ScriptManager.RegisterStartupScript(this, GetType(), "JScript", alert, true);
    }

    Note – For understanding the code, I have added the appropriate comments with the code.

    Final output of the above code – The watermark appears on the image in Cyan (Blue) color. The text is “C# Corner”.

    Image saved in the folder with watermark–

So this was a simple application where we played with images while uploading it to a folder. Hope you liked it and that this article helped you... Don’t forget to leave your comments. It always encourages me to move ahead... Smile | :)

If you want to check the entire code, please find the attached code file with this article.

License

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

Share

About the Author

Shivanand Arur
Software Developer
India India
I am a Software Engineer and a MINDCRACKER MVP and I like to work and create web applications. I love ASP.NET, C# and also love to explore the various features of these technologies. Microsoft's .Net technology and C# language are my true love. I am passionate in learning new things especially related to the .Net Technology.
 
My hobbies are to read technical articles and various Blogs, listening good music, Playing my guitar, Gaming(sometimes).... I have developed a new hobbie after joining C# Corner which is nothing else but "Writing Articles"....
 
Writing Articles is something which I have recently started and is really helping me to learn and explore various topics which I never thought it would be.... Anyways that's it for now.... Thanks for viewing my Profile Smile | :)
Follow on   Twitter   Google+

Comments and Discussions

 
SuggestionSuggestion for using the "using" block. PinmemberPankaj Nikam15-Jan-13 14:44 

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

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

| Advertise | Privacy | Mobile
Web02 | 2.8.140916.1 | Last Updated 14 Jan 2013
Article Copyright 2013 by Shivanand Arur
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid