Image Resize In Asp.Net

Image Resize In Asp.Net

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

Design:

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

<!DOCTYPE html>

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

Code:

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));
            }
            else
            {
                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);
                System.Threading.Thread.Sleep(5000);
                
            }
        }
    }

    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);
        }
    }
}