Playing With Images in ASP.NET Using C#

Playing with Images

Hello friends, in this article we are going to learn a few things related to images and file upload control. I have divided this article into 3 sections. This article is for complete beginners who are working with the File Upload control and images and want to know about the following points:

  1. Finding the height and width of an Image.
  2. Appending a timestamp 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:

Image of my Sample Application

FileUpload-control-and-images-in-ASP.NET1.jpg

Explanation

1. Finding the height and width of an image

Sometimes in our application we can allow our users to upload their images. And sometimes we want them to upload an image of a specific dimension. For example - 450x900. Hence the following is the code for finding the height and width.

Code to check the height and width of an image

Default.aspx page code

The following is the code for the Default.aspx page:

  1. <%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>  
  2. <asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">  
  3. </asp:Content>  
  4. <asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">  
  5.     <h2>  
  6.         Welcome to ASP.NET!  
  7.     </h2>  
  8.     <p>  
  9.         Please Select an Image file:     
  10.         <asp:FileUpload ID="FUP_WatermarkImage" runat="server" />  
  11.     </p>  
  12.     <p>  
  13.         <asp:Button ID="btnUpload" runat="server" Text="Upload Image" onclick="btnUpload_Click" />  
  14.     </p>  
  15.     <p>  
  16.         <asp:Image ID="imgUploadedImage" runat="server" Width="250" Height="250" BorderColor="Black" BorderStyle="Solid" BorderWidth="1" />  
  17.     </p>  
  18. </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 whether the image height and width exceeds 250*250 dimension. If it does then I'll show an error message to the user and won't allow him to upload that image.

  1. protected void btnUpload_Click(object sender, EventArgs e)  
  2. {  
  3.     if (Fupload_WatermarkImage.HasFile)  
  4.     {  
  5.         string FileType = Path.GetExtension(Fupload_WatermarkImage.PostedFile.FileName).ToLower().Trim();   
  6.         // Checking the format of the uploaded file.  
  7.         if (FileType != ".jpg" && FileType != ".png" && FileType != ".gif" && FileType != ".bmp")  
  8.         {  
  9.             string alert = "alert('File Format Not Supported. Only .jpg, .png, .bmp and .gif file formats are allowed.');";  
  10.             ScriptManager.RegisterStartupScript(this, GetType(), "JScript", alert, true);  
  11.         }  
  12.         else  
  13.         {  
  14.             // Getting the stream of the selected image and assign it to the Image Object.  
  15.              System.Drawing.Image UploadedImage = System.Drawing.Image.FromStream(Fupload_WatermarkImage.PostedFile.InputStream);   
  16.             // Checking if the Width or height is greater than 250px  
  17.             if (UploadedImage.PhysicalDimension.Width > 250 || UploadedImage.PhysicalDimension.Height > 250)  
  18.              {  
  19.                 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 + ".');";  
  20.                 ScriptManager.RegisterStartupScript(this, GetType(), "JScript", alert, true);  
  21.              }  
  22.             else  
  23.              {  
  24.                 // SOME CODE COMES HERE...  
  25.              }  
  26.         }  
  27.     }  
  28. }   

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

Image indicating the width of the uploaded image

The following image shows indicating the width of the uploaded image:

FileUpload-control-and-images-in-ASP.NET2.jpg

Image indicating the height of the uploaded image

The following image shows indicating the height of the uploaded image:

FileUpload-control-and-images-in-ASP.NET3.jpg

Error message shown to the user

The following image shows the error message shown to the user:

FileUpload-control-and-images-in-ASP.NET4.jpg

2. Appending a timestamp with the image name while saving it

Sometimes a user might add an image with the same name twice. So in that case if you want to differentiate between the images then you can attach the current timestamp with the image name. The following is the code for doing that.

  1. // Getting the file name of the selected image  
  2. string FileName = Path.GetFileNameWithoutExtension(Fupload_WatermarkImage.PostedFile.FileName);   
  3. // Getting the file extension of the selected image  
  4. string FileExtension = Path.GetExtension(Fupload_WatermarkImage.PostedFile.FileName);   
  5. // Creating a complete relative path for storing the image. And also attaching the datetime stamp with the image name.  
  6. string path = "Watermarked Images/" + FileName + DateTime.Now.ToString("yyyy-MM-dd HHmmtt") + FileExtension;                     
  7. // Saving the Image.  
  8. Fupload_WatermarkImage.SaveAs(Server.MapPath(path));                     
  9. // Assigning the uploaded image url to the Image control.  
  10. imgUploadedImage.ImageUrl = path;  
  11.   
  12. if (!String.IsNullOrEmpty(imgUploadedImage.ImageUrl))  
  13. {  
  14.         // Showing a notification of success after uploading.  
  15.            string alert = "alert('Image uploaded successfully');";  
  16.          ScriptManager.RegisterStartupScript(this, GetType(), "JScript", alert, true);  
  17. } 

Note: You can easily understand the code, since I have added appropriate comments with each line of my code. The line of code marked in yellow is where I am attaching my current timestamp with the image name.

Selected an image with a height and width less than 250 pixels

The following is the image which shows how exactly the image is saved.

FileUpload-control-and-images-in-ASP.NET5.jpg

Code Debugged

The following is the debugged code:

FileUpload-control-and-images-in-ASP.NET6.jpg

The current time is attached with the image name. So the next time, even if I upload the 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

The following shows the final output; the image being displayed in the Image Control:

FileUpload-control-and-images-in-ASP.NET7.jpg

Image uploaded in the folder

The following shows the image uploaded to the folder:

FileUpload-control-and-images-in-ASP.NET8.jpg

3. Watermarking the Image

Sometimes when we add images from our application, we do not want anyone else to copy it or use it in their application. Hence the watermark is the option which helps to protect our images from getting copied or used by other users. The following is the code written to add a watermark on the image before saving it in the folder.

Code for watermarking: The content marked in yellow actually writes / watermarks the image.

 

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

Note - For understanding the code, I have added appropriate comments with the code. The content marked in Yellow is the code for adding the watermark.

Final Output of the above Code: The Watermark appears on the image in Cyan (Blue) color. The text is "C# Corner"

FileUpload-control-and-images-in-ASP.NET9.jpg

Image saved in the folder with watermark

The following shows the image saved in the folder with the watermark:

FileUpload-control-and-images-in-ASP.NET10.jpg

So this was a simple application where we played with images while uploading them to the folder. Hope you liked it and this article helped you... Don't forget to leave your comments. It always encourages me to move ahead.

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


Similar Articles