5,427,303 members and growing! (14,918 online)
Email Password   helpLost your password?
Web Development » Charts, Graphs and Images » Images and multimedia     Intermediate

Dynamically resize uploaded images & save in PNG format

By 'Anil' Radhakrishna

Overcome the problem of image quality deterioration on resizing by converting to PNG format.
C#.NET 1.0, Win2K, WinXP, Windows, .NET, ASP.NET, Visual Studio, Dev

Posted: 7 May 2003
Updated: 7 May 2003
Views: 184,997
Bookmarked: 100 times
Announcements
Want a new Job?



Search    
Advanced Search
Sitemap
Prize winner in Competition "ASP.NET Apr 2003"
25 votes for this Article.
Popularity: 5.73 Rating: 4.10 out of 5
3 votes, 12.0%
1
2 votes, 8.0%
2
0 votes, 0.0%
3
6 votes, 24.0%
4
14 votes, 56.0%
5

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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

'Anil' Radhakrishna


'Anil' Radhakrishna is a seasoned developer and a Microsoft MVP (ASP/ASP.NET). He blogs his little discoveries and Web development tips, tricks and trivia quite regularly. You can find some of his unusual code samples & snippets at his Code Gallery.

Occupation: Web Developer
Location: India India

Other popular Charts, Graphs and Images articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 25 of 34 (Total in Forum: 34) (Refresh)FirstPrevNext
Subject  Author Date 
General1 problemmemberbarbod_blue19:06 22 Feb '08  
Questionwonderful scriptmemberdanielix5:42 7 Dec '07  
QuestionPNG 8Bit C#membervitor.duarte1:55 18 Dec '06  
QuestionVisual Basic CodememberKMOwen20:58 28 Oct '06  
QuestionPNG Uploader - Overwritememberdwhite0221:34 25 Oct '06  
GeneralThe process cannot access the file "D:\test\pics\top.jpg" because it is being used by another process.membershyrik14:35 15 Sep '06  
GeneralRe: The process cannot access the file "D:\test\pics\top.jpg" because it is being used by another process.memberChris Cameron13:34 29 Nov '06  
GeneralRe: The process cannot access the file "D:\test\pics\top.jpg" because it is being used by another process.memberGerryHeidenreich6:06 27 Sep '07  
GeneralPoor quality after resizememberedika20008:53 26 Feb '06  
GeneralWhy the Dummy CallBackmemberemadadelme3:31 9 Feb '06  
GeneralUpload, Resize and Thumbnailsmemberzioturo1:31 2 Nov '05  
GeneralRe: Upload, Resize and Thumbnailsmembergauty0:04 12 Jan '06  
GeneralI have this problemsusspmore1:44 27 Oct '05  
GeneralResize Images Problemsmembergmachado084:18 21 May '05  
Generalmore universal resizing solutionsussAnonymous11:50 3 Apr '05  
Generalgood article, but i have a better solutionsussAnoynomus17:41 19 Oct '04  
GeneralRe: good article, but i have a better solutionsussAnoynomus4:14 22 Oct '04  
GeneralRe: good article, but i have a better solutionsussAnonymous14:44 20 Feb '05  
GeneralRe: good article, but i have a better solutionmemberJeffrey Scott Flesher18:38 26 Jul '05  
GeneralRe: good article, but i have a better solutionmemberbharathreddyd7:33 11 Jul '06  
GeneralRe: Problem saving to a databasememberwallapa20:45 23 Oct '07  
AnswerRe: good article, but i have a better solutionmemberuswebpro28:55 3 Sep '07  
GeneralRe: good article, but i have a better solutionmemberMember 247356810:08 9 Aug '08  
Generalcode to display files and downloadsussAnonymous0:21 22 Sep '04  
GeneralI need some help