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 
<asp:Panel runat="server">;
<asp:FileUpload ID="fileupload1" runat="server" />
<asp:Button ID="btnsave" runat="server" Text="Upload" OnClick="btnsave_Click" />
</div>
<div>
<asp:DataList ID="dtlist" runat="server" RepeatColumns="3" CellPadding="5">
<ItemTemplate>
    <asp:Image ID="Image1" ImageUrl='<%# Bind("Name", "~/Images1/{0}") %>' runat="server" />
    <asp:HyperLink ID="HyperLink1" Text='<%# Bind("Name") %>' NavigateUrl='<%# Bind("Name", "~/Images1/{0}") %>' 
runat="server" /> </ItemTemplate> <ItemStyle BorderColor="Brown" BorderStyle="dotted" BorderWidth="3px" HorizontalAlign="Center" VerticalAlign="Bottom" /> </asp:DataList> </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.
Code Behind Page 
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindDataList();
}
}
protected void BindDataList()
{
DirectoryInfo dir = new DirectoryInfo(MapPath("Images1"));
FileInfo[] files = dir.GetFiles();
ArrayList listItems = new ArrayList();
foreach (FileInfo info in files)
{
listItems.Add(info);
}
dtlist.DataSource = listItems;
dtlist.DataBind();
}
protected void btnsave_Click(object sender, EventArgs e)
{
string filename = Path.GetFileName(fileupload1.PostedFile.FileName);
string targetPath = Server.MapPath("Images1/" + filename);
Stream strm = fileupload1.PostedFile.InputStream;
var targetFile = targetPath;
//Based on scalefactor image size will vary
GenerateThumbnails(0.5, strm, targetFile);
BindDataList();
}
private void GenerateThumbnails(double scaleFactor, Stream sourcePath,
string targetPath)
{
using (var image = Image.FromStream(sourcePath))
{
// can given width of image as we want
var newWidth = (int)(image.Width * scaleFactor); 
// can given height of image as we want
var newHeight = (int)(image.Height * scaleFactor);
var thumbnailImg = new Bitmap(newWidth, newHeight);
var thumbGraph = Graphics.FromImage(thumbnailImg);
thumbGraph.CompositingQuality = CompositingQuality.HighQuality;
thumbGraph.SmoothingMode = SmoothingMode.HighQuality;
thumbGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
var imageRectangle = new Rectangle(0, 0, newWidth, newHeight);
thumbGraph.DrawImage(image, imageRectangle);
thumbnailImg.Save(targetPath, image.RawFormat);
}           
} 

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
<system.web>
<httpRuntime executionTimeout="240" maxRequestLength="20480" />
</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:

<<location path="Upload">
<system.web>
<httpRuntime executionTimeout="110" maxRequestLength="20000" />
</system.web>
</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:

System.Configuration.Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
HttpRuntimeSection section = config.GetSection("system.web/httpRuntime") as HttpRuntimeSection;
double maxFileSize = Math.Round(section.MaxRequestLength / 1024.0, 1);
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.