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

Dynamically resize uploaded images & save in PNG format

Rate me:
Please Sign up or sign in to vote.
4.80/5 (38 votes)
7 May 2003CPOL1 min read 413.2K   8.6K   161   39
Overcome the problem of image quality deterioration on resizing by converting to PNG format.

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.

C#
<%@ 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)


Written By
Architect
India India
'Anil' Radhakrishna is a seasoned architect 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. He loves building mash-ups using public Web APIs.

Comments and Discussions

 
GeneralI need some help Pin
lulu505016-Sep-04 4:57
lulu505016-Sep-04 4:57 
GeneralImage Resample Pin
Troy Wolf28-Sep-03 10:20
Troy Wolf28-Sep-03 10:20 
GeneralRe: Image Resample Pin
Mergen AGAYEV21-Nov-06 12:57
Mergen AGAYEV21-Nov-06 12:57 
QuestionRe: Image Resample Pin
imwavygravy28-Jun-07 2:26
imwavygravy28-Jun-07 2:26 
GeneralPermissions Pin
Guy Harwood7-Jul-03 22:49
Guy Harwood7-Jul-03 22:49 
GeneralRe: Permissions Pin
Anonymous24-Jul-03 0:23
Anonymous24-Jul-03 0:23 
GeneralScaling Images Pin
chlock18-Jun-03 20:04
chlock18-Jun-03 20:04 
GeneralRe: Scaling Images Pin
Spider-Man18-Aug-03 12:05
Spider-Man18-Aug-03 12:05 
Unfortunatly, the base article blew it when it came to resizing images..

DO NOT USE THIS METHOD FOR RESIZING IMAGES IN .NET!!

If you have images that are submitted by users and one of them takes a submits a .Jpg file with a embedded thumbnail, the code will not function.
Well, it will show a thumbnail that will look bad until you return the full image.

This is because the function 'image.GetThumbnailImage' is DESIGNED to extract out the thumbnail image from a image - NOT to scale the original image to create a thumbnail. (Which is exactly what it says in the help!)
(take an Image from a Minolta 7i or 7hi camera to get a good example of a .jpg with an embedded thumbnail)

So, here is what happens.. I start off with an image that is 2560x1920 that looks good, I call image.GetThumbnailImage(50,...) to get a small image that is 50 pixels wide.. it looks pretty good...

But if I call image.GetThumbnailImage(400,...) it looks like total crud - that is because it took the small thumbnail image embedded in the .jpg (maybe 100x80 or smaller) and streched it to be 400 wide... Now each pixel is a block of about 10 pixels wide... If you make this 1024 wide you get a real mess..

So, instead of doing that, just call:

Image Img; // Original

Image Thumb = new Bitmap (Img, NewWidth, NewHeight);

And Use the new thumbnail... Not only is it correct, it is MUCH cleaner code! Goodness knows why someone wrote the interface they did on GetThumbnailImage!!! Confused | :confused:

-Chert

PS: I tried using .png files instead of .jpg files, and got wonderfuly bad results.. the pictures were just about the same appearence, but instead of being small, I got this:
    6,669 PICT1134-0.jpg       50 pixels wide
   52,987 PICT1134-0.png       Same.

   46,249 PICT1134-1.jpg      400 pixels wide
  555,106 PICT1134-1.png      Same. over 10X larger!!!

  143,987 PICT1134-2.jpg      1024 pixels wide
2,278,688 PICT1134-2.png      Same.  Almost 16X larger!

So, sure it might be a little better, but the last image file is only a little smaller than my original 5 Mp image!

Doesn't that pretty much defeat the point of making it a thumbnail?

(I used the default values to save, calling save with only ImageFormat.png or .Jpeg)

-Chert
GeneralImage size Pin
Gunmen9-May-03 0:53
Gunmen9-May-03 0:53 
GeneralRe: Image size Pin
talking10-Jun-03 19:08
talking10-Jun-03 19:08 

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.