How to Resize Image While Uploading in Asp.net C#

/ / 13 Comments
[ads]Resize Image in Asp.net c#: This post explains how to resize images in ASP.Net C# during uploading image file. Basically, we are Resizing and processing images as they are uploaded on the server in Asp.net C#. For we Dotnet Developer in most of our ASP.Net application, we have uploading image facility. Here we face the performance issue while uploading large size images to display for the user. In my project, there is a similar requirement that the user upload images will be resized and renamed internally through server side while uploading. I have a default.aspx page which will upload images to the server hard disk from client PC.  And I need to write a program in such a way that it would allow me to resize the image while uploading. This program (C# code)  also can be used to create thumbnail .i.e  calling this function we can resize the uploaded image to a thumbnail size 100 X 100.

Here’s the code for resizing an image in Asp.net C# while uploading:

 Firstly, we are going to add the following namespaces in our Webform (Asp.net Web Application)

System.Drawing;
System.Drawing.Drawing2D

HTML Markup: Adding File control and button on webpage.

Here we added an Asp.net Fileupload control and button, so we can resize the image to a smaller size and then save it to the server.

<asp:fileupload id=”File1″ runat=”server”>
</asp:fileupload>
<asp:button id=”Button1″ onclick=”Button1_Click” runat=”server” text=”Save”>
<asp:label id=”lblmsg” runat=”server” text=””></asp:label>
</asp:button>

Code behind: Code to save and resize image uploaded.

Boom !! This is the masterpiece code.

Here's in the below given code we have a  method which has two parameters, retrieve as image and height, after retrieving image and height based on its ratio the image gets resized.

Run this code and you will see whenever the user uploads an image then our masterpiece C# code will resize the image to the appropriate size by setting its height or weight. Also, note we are going to maintain image ratio

public static System.Drawing.Image ScaleImage(System.Drawing.Image image, int maxHeight)
    {
        var ratio = (double)maxHeight / image.Height;
        var newWidth = (int)(image.Width * ratio);
        var newHeight = (int)(image.Height * ratio);
        var newImage = new Bitmap(newWidth, newHeight);
        using (var g = Graphics.FromImage(newImage))
        {
            g.DrawImage(image, 0, 0, newWidth, newHeight);
        }
        return newImage;
    }

Here's full Code to save and resize the image, also we have applied some validation i.e only image file get uploaded by checking file extension .png, .gif, .jpeg, also checking image size limit.

You can also check  how to Preview Image before upload in Asp.net c# using jQuery if you want the user, to view thumbnail photos on the client side i.e before uploading to the server.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
public partial class UploadLogo : System.Web.UI.Page
{
    public Size OriginalImageSize { get; set; }        //Store original image size.
    public Size NewImageSize { get; set; }
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        lblmsg.Text="";
        if ((File1.PostedFile != null) && (File1.PostedFile.ContentLength > 0))
        {
            Guid uid = Guid.NewGuid();
            string fn = System.IO.Path.GetFileName(File1.PostedFile.FileName);
            string SaveLocation = Server.MapPath("LogoImages") + "" + uid+fn;
            try
            {
                string fileExtention = File1.PostedFile.ContentType;
                int fileLenght = File1.PostedFile.ContentLength;
                if (fileExtention == "image/png" || fileExtention == "image/jpeg" || fileExtention == "image/x-png")
                {
                   if (fileLenght <= 1048576)
                    {
                        System.Drawing.Bitmap bmpPostedImage = new System.Drawing.Bitmap(File1.PostedFile.InputStream);
                        System.Drawing.Image objImage = ScaleImage(bmpPostedImage, 81);
                        // Saving image in jpeg format
                        objImage.Save(SaveLocation,ImageFormat.Jpeg);
                        lblmsg.Text = "The file has been uploaded.";
                        lblmsg.Style.Add("Color", "Green");
                    }
                    else{
                            lblmsg.Text = "Image size cannot be more then 1 MB.";
                            lblmsg.Style.Add("Color", "Red");
                          }
                }
                else {
                        lblmsg.Text = "Invaild Format!";
                        lblmsg.Style.Add("Color", "Red");
                       }
            }
            catch (Exception ex)
            {
                lblmsg.Text= "Error: " + ex.Message;
                lblmsg.Style.Add("Color", "Red");
            }
        }
    }
}
You can also check these articles:
  1. An easy way to upload bulk images in Asp.net c#.
  2. Preview Image before uploading it with jQuery in Asp.net.
  3. Profile photo change with drag drop with Dropzone Js in Asp.net C#.
  [txt_ads]   Hope you enjoyed this tutorial. If you have any recommendations, please let us know what you think in the comment section below! See you again next time!

Thank you for reading, pls keep visiting this blog and share this in your network. Also, I would love to hear your opinions down in the comments.

PS: If you found this content valuable and want to do a favor, then Buy me a coffee

Subscribe to our newsletter

Get the latest and greatest from Codepedia delivered straight to your inbox.


Post Comment

Your email address will not be published. Required fields are marked *

13 Comments

  1. Anonymous 02/04/2013 07:23:00
    thanks
  2. Tomas 04/03/2015 09:31:24
    Thank you for this. I just change ImageFormat.Png to ImageFormat.Jpeg to compress resized file
  3. Satinder singh 04/03/2015 17:13:48
    @Tomas: yes its a good call to use ImageFormat.Jpeg as this also reflect file size. Thanks will updated in my article too :-)
  4. prasunjeet soni 01/15/2016 07:54:15
    I have tried this code but an error that ScaleImage not available in current context.I imported all namespaces which you metioned in example. I google many solution regarding this but could not get any solution so that ScaleImage could be available in current context. please provide valuable suggestion?
  5. Satinder singh 01/15/2016 10:24:01
    Hi Prasunjeet Soni, The error msg 'ScaleImage not available in current context' means, you have missed 'ScaleImage' method in your code. Pls check the article properly method ScaleImage returns the resized IMAGE
  6. Madhukar 09/29/2016 06:32:26
    i have got error on these lines if((File1.PostedFile!=null)&&(File1.PostedFile.ContentLength > 0)) fileLength <= 1048576 what does that &gt" and "&lt" means?"
  7. Eric 06/04/2017 16:28:37
    I used the code and it worked instantly. Only problem is that vertical images are rotated 90 degrees!? Horizontal images are ok but vertical images are changed and made horizontal? How can I stop this?
  8. Satinder singh 06/07/2017 17:37:04
    Hi Eric, Thank you for reading. For vertical images you need to make little changes in ScaleImage() function accordingly i.e set max width instead of height.
  9. Zakaria Mansoor 10/03/2017 22:45:38
    thank you, this is was helpful (Y)
  10. Satinder singh 10/26/2017 06:55:05
    Thanks Zakaria, Keep visiting :)
  11. Satinder singh 10/26/2017 07:16:03
    that mean arrow brackets i.e < and >
  12. PatP 12/11/2017 07:17:36
    Thank you for this! Very helpful and worked first try. Now I will be searching how to control the jpeg compression ratio for a bit better quality.
  13. Satinder singh 12/28/2017 17:14:15
    Am glad you like it. Keep visiting