image resizing in c# dynamically

In this article you can find the code that is for re-sizing images with given width and height and retain the quality of the image as it was.

below is the function just pass new width, new height and original image file path it will save resize given image and save it into the folder named newsizeimages and returns the new path.

Resize Image Code C#

public string CreateThumbnail(int maxWidth, int maxHeight, string path)

    var image = System.Drawing.Image.FromFile(path);
    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);
    Graphics thumbGraph = Graphics.FromImage(newImage);

    thumbGraph.CompositingQuality = CompositingQuality.HighQuality;
    thumbGraph.SmoothingMode = SmoothingMode.HighQuality;
    //thumbGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;

    thumbGraph.DrawImage(image, 0, 0, newWidth, newHeight);

    string fileRelativePath = "newsizeimages/" + maxWidth + Path.GetFileName(path);
    newImage.Save(Server.MapPath(fileRelativePath), newImage.RawFormat);
    return fileRelativePath;


In if you want to resize client uploaded image files directly when client uploading their image files then you have to save this files first into the server and then pass this file path into the above function as given below example.
if (updImage.HasFile)
   updImage.SaveAs(Server.MapPath("uploadedimage/" + updImage.FileName));

   imgCustomTo8.ImageUrl = CreateThumbnail(8, 8, Server.MapPath("uploadedimage/" + updImage.FileName));
   imgCustomTo16.ImageUrl = CreateThumbnail(16, 16, Server.MapPath("uploadedimage/" + updImage.FileName));
   imgCustomTo24.ImageUrl = CreateThumbnail(24, 24, Server.MapPath("uploadedimage/" + updImage.FileName));
   imgCustomTo32.ImageUrl = CreateThumbnail(32, 32, Server.MapPath("uploadedimage/" + updImage.FileName));


Download image re-sizing sample code click here.

Recent Article