Click here to Skip to main content
Click here to Skip to main content

Dynamically resize uploaded images & save in PNG format

By , 7 May 2003
 
Prize winner in Competition "ASP.NET Apr 2003"

Sample Image - PNGUploader.jpg

Introduction

Uploading images & storing them dynamically after resizing is a painless affair now using .NET, unlike what it used to be in Classic ASP. There are several good articles on uploading & resizing images on CodeProject (.NET Image Uploading [^], File Upload with ASP.NET [^], Thumbnail Image Creation and Image format Conversion Utility [^]) & elsewhere on the net (True Image Resizing [^]). One issue with resizing images is that the quality of the image deteriorates. This article is written in praise of the PNG image format & shows how the original quality of the uploaded image of any regular format can be maintained & even be improved.

PNG - What's it?

Check out this excellent article on the PNG image format - FAQ: Converting GIF or JPG to PNG [^]. To paraphrase the article -

  • PNG stands for Portable Network Graphics and pronounced "ping".
  • PNG is supported by the major browsers (Microsoft IE and Netscape 4.x and higher)
  • The images are a lot clearer, no more grainy GIF images or pixelated JPGs!

Source code

This application allows the user to set the dimensions for the image to be resized & uploaded. The resized image is converted into the W3C Portable Network Graphics (PNG) image format by using the PNG property of the ImageFormat class.

<%@ Page Language="C#" %>
<%@ import Namespace="System.Drawing.Imaging" %>
<script runat="server">
//Pics folder has to be created under the current folder
void UploadBtn_Click(Object sender, EventArgs e)
{      
    String UploadedFile = MyFile.PostedFile.FileName;
    int ExtractPos = UploadedFile.LastIndexOf("\\") + 1;
  
    //to retrieve only Filename from the complete path
    String UploadedFileName = UploadedFile.Substring(ExtractPos,UploadedFile.Length - ExtractPos);
       
    // Display information about posted file. Div is invisible by default   
    FileName.InnerHtml = UploadedFileName;
    
    MyContentType.InnerHtml = MyFile.PostedFile.ContentType;
    
    ContentLength.InnerHtml = MyFile.PostedFile.ContentLength.ToString();
    
    FileDetails.Visible = true; //div is made visible
 
    // Save uploaded file to server at the in the Pics folder
    MyFile.PostedFile.SaveAs(Request.PhysicalApplicationPath 
                            + "pics\\" + UploadedFileName );

   //thumbnail creation starts
   try
   {
      //Retrieve the image filename whose thumbnail has to be created
      String imageUrl =  UploadedFileName;
      //Read in the width and height
      int imageHeight =Convert.ToInt32(h.Text);
      int imageWidth  = Convert.ToInt32(w.Text); 
  
      //You may even specify a standard thumbnail size
      //int imageWidth  = 70; 
      //int imageHeight = 70;
  
      if (imageUrl.IndexOf("/") >= 0 || imageUrl.IndexOf("\\") >= 0 )
      {
         //We found a / or \
         Response.End();
      }
  
      //the uploaded image will be stored in the Pics folder.
      //to get resize the image, the original image has to be
      //accessed from the Pics folder
      imageUrl = "pics/" + imageUrl;
  
      System.Drawing.Image fullSizeImg 
              = System.Drawing.Image.FromFile(Server.MapPath(imageUrl));
      System.Drawing.Image.GetThumbnailImageAbort dummyCallBack 
              = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
      System.Drawing.Image thumbNailImg 
              = fullSizeImg.GetThumbnailImage(imageWidth, imageHeight, 
                                              dummyCallBack, IntPtr.Zero);
   
      //We need to create a unique filename for each generated image
      DateTime MyDate = DateTime.Now;
  
      String MyString  = MyDate.ToString("ddMMyyhhmmss") + ".png" ;
 
      //Save the thumbnail in PNG format. 
      //You may change it to a diff format with the ImageFormat property
      thumbNailImg.Save ( Request.PhysicalApplicationPath 
                          + "pics\\" +   MyString , ImageFormat.Png);
      thumbNailImg.Dispose();
   
      //Display the original & the newly generated thumbnail
   
      Image1.AlternateText = "Original image";  
      Image1.ImageUrl="pics\\" + UploadedFileName;
      Image2.AlternateText = "Thumbnail";
      Image2.ImageUrl="pics\\" + MyString;
   }
   catch(Exception ex)
   {
      Response.Write("An error occurred - " + ex.ToString());
   }
}
  
//this function is reqd for thumbnail creation
public bool ThumbnailCallback()
{
   return false;
}
</script>

How to run the app

Unzip & run the .aspx file using IIS. Make sure a folder named PICS is created before-hand in the current working directory.

Conclusion

This article demonstrates how the quality of dynamically created images can be maintained & even enhanced by saving them in PNG format.

License

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

About the Author

'Anil' Radhakrishna
Web Developer
India India
Member
'Anil' Radhakrishna is a seasoned developer who enjoys working with Microsoft tools & technologies. He blogs quite regularly about his little discoveries and technical experiments on his blog called Tech Tips, Tricks & Trivia. You can find some of his unusual code samples & snippets at his Code Gallery. He loves building mash-ups using public Web APIs.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 1memberrhandler27 Dec '10 - 10:02 
GeneralMy vote of 1memberamit.comp120 Dec '10 - 23:50 
General1 problemmemberbarbod_blue22 Feb '08 - 18:06 
AnswerRe: 1 problem - solutionmemberjohannesnestler11 Nov '08 - 23:33 
GeneralRe: 1 problemmember<span style="forecolor:red">apr ~ asp</sp23 Mar '09 - 5:21 
Questionwonderful scriptmemberdanielix7 Dec '07 - 4:42 
QuestionPNG 8Bit C#membervitor.duarte18 Dec '06 - 0:55 
QuestionVisual Basic CodememberKMOwen28 Oct '06 - 19:58 
QuestionPNG Uploader - Overwritememberdwhite0225 Oct '06 - 20:34 
GeneralThe process cannot access the file "D:\test\pics\top.jpg" because it is being used by another process.membershyrik15 Sep '06 - 13:35 
GeneralRe: The process cannot access the file "D:\test\pics\top.jpg" because it is being used by another process.memberChris Cameron29 Nov '06 - 12:34 
GeneralRe: The process cannot access the file "D:\test\pics\top.jpg" because it is being used by another process.memberGerryHeidenreich27 Sep '07 - 5:06 
GeneralPoor quality after resizememberedika200026 Feb '06 - 7:53 
GeneralWhy the Dummy CallBackmemberemadadelme9 Feb '06 - 2:31 
GeneralUpload, Resize and Thumbnailsmemberzioturo2 Nov '05 - 0:31 
GeneralRe: Upload, Resize and Thumbnailsmembergauty11 Jan '06 - 23:04 
GeneralI have this problemsusspmore27 Oct '05 - 0:44 
GeneralResize Images Problemsmembergmachado0821 May '05 - 3:18 
Generalmore universal resizing solutionsussAnonymous3 Apr '05 - 10:50 
Generalgood article, but i have a better solutionsussAnoynomus19 Oct '04 - 16:41 
GeneralRe: good article, but i have a better solutionsussAnoynomus22 Oct '04 - 3:14 
GeneralRe: good article, but i have a better solutionsussAnonymous20 Feb '05 - 13:44 
GeneralRe: good article, but i have a better solutionmemberJeffrey Scott Flesher26 Jul '05 - 17:38 
GeneralRe: good article, but i have a better solutionmemberbharathreddyd11 Jul '06 - 6:33 
GeneralRe: Problem saving to a databasememberwallapa23 Oct '07 - 19:45 

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

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130516.1 | Last Updated 8 May 2003
Article Copyright 2003 by 'Anil' Radhakrishna
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid