How to Resize Image While Uploading in C#

satinder singh / Updated : / 15 Comments

Resize Image in 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 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 C# while uploading:

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


HTML Markup: Adding File control and button on webpage.

Here we added an 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:button id=”Button1″ onclick=”Button1_Click” runat=”server” text=”Save”>
<asp:label id=”lblmsg” runat=”server” text=””></asp:label>

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 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)
        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;
                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
                        lblmsg.Text = "The file has been uploaded.";
                        lblmsg.Style.Add("Color", "Green");
                            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 c#.
  2. Preview Image before uploading it with jQuery in
  3. Profile photo change with drag drop with Dropzone Js in 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!

15 comments on “How to Resize Image While Uploading in C#”

  1. PatP

    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.

  2. Eric

    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?

  3. Madhukar

    i have got error on these lines
    if((File1.PostedFile!=null)&&(File1.PostedFile.ContentLength > 0))
    fileLength <= 1048576

    what does that “&gt” and “&lt” means?

  4. 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 *