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

/ / 13 Comments

Resize Image in Asp.net c#: This post explains how to resize images in ASP.Net C# during uploading image files. 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 applications, we have an 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 the server-side while uploading. I have a default.aspx page which will upload images to the server hard disk from the 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 a thumbnail .i.e By 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 the 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 the 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 the full Code to save and resize the image, also we have applied some validation i.e only image files 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#.

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 thank me? 👳 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 :-)