Image Resize In Asp.Net

Image Resize In Asp.Net

In this post we will learn how to resize a image while uploading in or Image Resize In Asp.Net.We are not using any other kind of functionality here, we are simply using features.We are at first detect file size and then change it’s size(resize).


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>

<html xmlns="">
<head runat="server">
<title>Image Resize In</title>
<body style="margin:0px auto;width:900px;text-align:center">
<form id="form1" runat="server">
<h2>Image Resize In</h2>
<asp:FileUpload ID="FileUpload1" runat="server" />
<br />
<br />
<asp:Button runat="server" ID="submit" Text="Upload" OnClick="submit_Click" />


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;

public partial class _Default : System.Web.UI.Page
    protected void Page_Load(object sender, EventArgs e)

    protected void submit_Click(object sender, EventArgs e)
        String profilepic = "";
        if (FileUpload1.HasFile)
            int imgSize = FileUpload1.PostedFile.ContentLength;

            if (imgSize <= 409600)
                profilepic = FileUpload1.FileName.ToString();
                FileUpload1.SaveAs(MapPath("~\\IMG\\" + profilepic));
                profilepic = Path.GetFileName(FileUpload1.PostedFile.FileName);
                string targetPath = Server.MapPath("~\\IMG\\" + profilepic);
                Stream strm = FileUpload1.PostedFile.InputStream;
                var targetFile = targetPath;
                GenerateThumbnails(0.3, strm, targetFile);

    private void GenerateThumbnails(double scaleFactor, Stream sourcePath, string targetPath)
        using (var image = System.Drawing.Image.FromStream(sourcePath))
            var newWidth = (int)(image.Width * scaleFactor);
            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);