c# .net

How to resize an Image at run-time in C# asp.Net?

How to resize an Image at run-time in C# asp.Net?, someone asked me to explain?

In this article you will learn about how to resize an Image at run-time using C# asp.Net.Resize an image with good quality, and having less weight of an image so that webpages will load it faster.

should reference the following namespases.

using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
#region Events 
protected void ResizeButton_click(object sender,EventArgs e)
string path = Server.MapPath("~/Images");
public static void ResizePhoto(string imgpath)
//if you want dynamically to change images set path insead of 3904.jpg
using (var image = System.Drawing.Image.FromFile(string.Concat(imgpath, "/3904.jpg")))
using (var newImage = ScaleImage(image, 350, 450))
// dynamically change the name of new size image by any customized name (e.g:datetime )
newImage.Save(string.Concat(imgpath, "/test.jpg"), ImageFormat.Png);

public static System.Drawing.Image ScaleImage(System.Drawing.Image image, int maxWidth, int maxHeight)
var ratioX = (double)maxWidth / image.Width;
var ratioY = (double)maxHeight / image.Height;
var ratio = Math.Min(ratioX, ratioY);

var newWidth = (int)(image.Width * ratio);
var newHeight = (int)(image.Height * ratio);

var newImage = new Bitmap(newWidth, newHeight);

using (var graphics = Graphics.FromImage(newImage))
graphics.DrawImage(image, 0, 0, newWidth, newHeight);

return newImage;

Post your comments / questions