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

Resize Image in Asp.net: 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 .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 resize image in Asp.net C# while upload:

 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 below given code we have a  method which have two parameters, retrieve as  image and height, after retrieving image and height  based on it 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 are 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 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. Easy way to upload bulk images in Asp.net c#.
  2. Preview Image before upload it with jQuery in Asp.net.
  3. Profile photo change with drag drop with Dropzone Js in Asp.net C#.

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!

Share:    
Satinder Singh

Hi all, am Founder and Author of Codepedia.info, also atypical polyglot programmer from Bombay, India. I have a passion to create, solve, and deploy software applications.
       ForEach ( minute in MyLife ) { myExperience++ ; }


5 comments on “How to Resize Image While Uploading in Asp.net C#”

  1. prasunjeet soni

    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?

    • Satinder singh

      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


Post Comment


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