Reduce image size/ Generate thumbnails

Most web applications have performance issue with loading user uploaded images. However, we can limited the maximum size of the image that a user can upload but it may not be feasible as nowadays with digital cameras 5-6 MB size is normal.

The only solution is to reduce image size either by user or by web application. To give users ease-of-use and as SE(Software Engineering) says developer should do it in back end while saving image. We are internally reducing the size of the image that a user going to upload by checking whether it is exceeds affordable size. Then there is no constraints are given to user so that he doesn't care about the size and quality of the image.

Image Size 5.21 MB


GENERATE THUMBNAIL | ASP.NET | C# | RESIZE LARGE IMAGE | SYSTEM.DRAWING; | SYSTEM.DRAWING.DRAWING2D; | RESIZE LARGE IMAGE ASP.NET C# | HOW TO ASP.NET | HOW TO C# | HttpRuntime


Simple steps to reduce the size of image before upload in ASP.Net/C#

In most cases we don't need to show widescreen images instead needs to show thumbnails(reduce size) or say

800x600 PX. So it is advisable to not overload server by saving high definition images and make it small before saving on server.

So following is the steps to develop a test application.

  • Step 1 . Create a ASP.Net project and create a web page.
  • Step 2. Drag a file uploader, button and Datalist(for display uploaded images)

ASPX Page
  1. <asp:Panel runat="server">;  
  2.     <asp:FileUpload ID="fileupload1" runat="server" />  
  3.     <asp:Button ID="btnsave" runat="server" Text="Upload" OnClick="btnsave_Click" />  
  4.     <div></div>  
  5.     <asp:DataList ID="dtlist" runat="server" RepeatColumns="3" CellPadding="5">  
  6.     <ItemTemplate>  
  7.         <asp:Image ID="Image1" ImageUrl='<%# Bind("Name", "~/Images1/{0}") %>' runat="server" />  
  8.         <asp:HyperLink ID="HyperLink1" Text='<%# Bind("Name") %>' NavigateUrl='<%# Bind("Name", "~/Images1/{0}") %>' runat="server" />  
  9.         </ItemTemplate>  
  10.         <ItemStyle BorderColor="Brown" BorderStyle="dotted" BorderWidth="3px"  HorizontalAlign="Center" VerticalAlign="Bottom" />  
  11.     </asp:DataList>  
  12. </asp:Panel>  
 
  • Step 3 . In page load call function ‘BindDataList' to display uploaded imagesi>
  • Step 4. On Save button click event, call function ‘GenerateThumbnails' for reduce of image.
  1. protected void BindDataList()  
  2. {  
  3.     DirectoryInfo dir = new DirectoryInfo(MapPath("Images1"));  
  4.     FileInfo[] files = dir.GetFiles();  
  5.     ArrayList listItems = new ArrayList();  
  6.     foreach (FileInfo info in files)  
  7.     {  
  8.         listItems.Add(info);  
  9.     }  
  10.     dtlist.DataSource = listItems;  
  11.     dtlist.DataBind();  
  12. }  
  13. protected void btnsave_Click(object sender, EventArgs e)  
  14. {  
  15.     string filename = Path.GetFileName(fileupload1.PostedFile.FileName);  
  16.     string targetPath = Server.MapPath("Images1/" + filename);  
  17.     Stream strm = fileupload1.PostedFile.InputStream;  
  18.     var targetFile = targetPath;  
  19.     //Based on scalefactor image size will vary  
  20.     GenerateThumbnails(0.5, strm, targetFile);  
  21.     BindDataList();  
  22. }  
  23. private void GenerateThumbnails(double scaleFactor, Stream sourcePath,  
  24. string targetPath)  
  25. {  
  26.     using (var image = Image.FromStream(sourcePath))  
  27.     {  
  28.         // can given width of image as we want  
  29.         var newWidth = (int)(image.Width * scaleFactor);  
  30.         // can given height of image as we want  
  31.         var newHeight = (int)(image.Height * scaleFactor);  
  32.         var thumbnailImg = new Bitmap(newWidth, newHeight);  
  33.         var thumbGraph = Graphics.FromImage(thumbnailImg);  
  34.         thumbGraph.CompositingQuality = CompositingQuality.HighQuality;  
  35.         thumbGraph.SmoothingMode = SmoothingMode.HighQuality;  
  36.         thumbGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;  
  37.         var imageRectangle = new Rectangle(0, 0, newWidth, newHeight);  
  38.         thumbGraph.DrawImage(image, imageRectangle);  
  39.         thumbnailImg.Save(targetPath, image.RawFormat);  
  40.     }  
  41. }   

Image after compression. 223 KB


GENERATE THUMBNAIL | ASP.NET | C# | RESIZE LARGE IMAGE | SYSTEM.DRAWING; | SYSTEM.DRAWING.DRAWING2D; | RESIZE LARGE IMAGE ASP.NET C# | HOW TO ASP.NET | HOW TO C# | HttpRuntime


  • Step 5 . Configure web.config to increase Http Request default size
Web.config
  1. <system.web>  
  2.     <httpRuntime executionTimeout="240" maxRequestLength="20480" />  
  3. </system.web>  

The default maximum filesize is 4MB - this is done to prevent denial of service attacks in which an attacker submitted one or more huge files which overwhelmed server resources. If a user uploads a file larger than 4MB, they'll get an error message: "Maximum request length exceeded." The 4MB default is set in machine.config, but you can override it in you web.config. Since the maximum request size limit is there to protect your site, it's best to expand the file-size limit for specific directories rather than your entire application. That's possible since the web.config allows for cascading overrides. You can add a web.config file to your folder which just contains the above, or you can use the <location> tag in your main web.config to achieve the same effect:
  1. <location path="Upload">  
  2.     <system.web>  
  3.         <httpRuntime executionTimeout="110" maxRequestLength="20000" />  
  4.     </system.web>  
  5. </location>  

At Least Give Me A Warning

If we've got a set limit on file upload sizes, we should at least tell our users what it is. Since this is a configurable value which we may change later, the best is to make our file size warning read directly from web.config setting. The best way to do this is to pull back the httpRuntime section as a HttpRuntimeSection object, which isn't too hard given:

  1. System.Configuration.Configuration config = WebConfigurationManager.OpenWebConfiguration("~");  
  2. HttpRuntimeSection section = config.GetSection("system.web/httpRuntime"as HttpRuntimeSection;  
  3. double maxFileSize = Math.Round(section.MaxRequestLength / 1024.0, 1);  
  4. FileSizeLimit.Text = string.Format("Make sure your file is under {0:0.#} MB.", maxFileSize);  

By using above application, we can reduce the size of images before uploaded to the server. If we check the size of the image that we uploaded, that will be less than the size of image that having in the local folder. So we can easily reduce the resolution of the image using above code in ASP.Net/C# application.