How To Resize Large Image With Good Quality Using C# Coding

How To Resize Large Image With Good Quality Using C# Coding

Large image files can impact application performance, increase storage requirements, and slow down page loading times.

Whether you are building an ASP.NET application, desktop software, content management system, or eCommerce platform, image optimization is essential for delivering a better user experience.

One of the most common requirements in .NET development is resizing images while maintaining their visual quality and aspect ratio.

Developers often need to generate thumbnails, resize uploaded images, optimize bitmap files, or adjust image dimensions before storing them in a database or file system.

In this article, we will demonstrate how to resize large images in C# with good quality using ASP.NET MVC.

The example shows how to calculate proportional dimensions, preserve image quality during resizing, and generate optimized images suitable for web applications.

Why Resize Images in C#?

Resizing images is a common requirement in many business applications and websites.

Uploading original high-resolution images directly can consume excessive storage space and increase bandwidth usage.

By resizing images before displaying or storing them, applications can improve performance and reduce resource consumption.

Common use cases for image resizing in C# include:

  • Creating thumbnail images for galleries and product listings
  • Reducing image size before uploading to a server
  • Generating optimized images for web applications
  • Preparing images for reports and documents
  • Adjusting image dimensions for mobile devices
  • Scaling bitmap images while preserving aspect ratio
The following example demonstrates a practical approach to resizing large images while maintaining image quality using C# and ASP.NET MVC.

Steps:

  1. Select Image which you want to Resize and upload on the server.
    Select Image which you want to Resize and upload on the server
  2. Go to the Controller section and add the following assemblies. Create function of “ResizeImage()” in controller.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Drawing;
using Watermark;
using System.Windows.Forms;
using System.IO;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;

namespace ResizeLargeImageWithGoodQuality.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index(string imgName)
        {
            ViewBag.ImgName = imgName;
            return View();
        }

        public ActionResult UploadImageThumb(HttpPostedFileBase fileToUpload)
        {
            string myfile = ResizeImage(fileToUpload);
            return RedirectToAction("Index", new { imgName = myfile });
        }

        public string ResizeImage(HttpPostedFileBase fileToUpload)
        {
            string name = Path.GetFileNameWithoutExtension(fileToUpload.FileName);
            var ext = Path.GetExtension(fileToUpload.FileName);
            string myfile = name + ext;

            try
            {
                using (Image image = Image.FromStream(fileToUpload.InputStream, true, false))
                {

                    var path = Path.Combine(Server.MapPath("~/resizeImageStore"), myfile);
                    try
                    {
                        //Size can be change according to your requirement 
                        float thumbWidth = 270F;
                        float thumbHeight = 180F;
                        //calculate  image  size
                        if (image.Width > image.Height)
                        {
                            thumbHeight = ((float)image.Height / image.Width) * thumbWidth;
                        }
                        else
                        {
                            thumbWidth = ((float)image.Width / image.Height) * thumbHeight;
                        }

                        int actualthumbWidth = Convert.ToInt32(Math.Floor(thumbWidth));
                        int actualthumbHeight = Convert.ToInt32(Math.Floor(thumbHeight));
                        var thumbnailBitmap = new Bitmap(actualthumbWidth, actualthumbHeight);
                        var thumbnailGraph = Graphics.FromImage(thumbnailBitmap);
                        thumbnailGraph.CompositingQuality = CompositingQuality.HighQuality;
                        thumbnailGraph.SmoothingMode = SmoothingMode.HighQuality;
                        thumbnailGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        var imageRectangle = new Rectangle(0, 0, actualthumbWidth, actualthumbHeight);
                        thumbnailGraph.DrawImage(image, imageRectangle);
                        var ms = new MemoryStream();
                        thumbnailBitmap.Save(path, ImageFormat.Jpeg);
                        ms.Position = 0;
                        GC.Collect();
                        thumbnailGraph.Dispose();
                        thumbnailBitmap.Dispose();
                        image.Dispose();
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return myfile;
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }
}

  1. For we use large images for resizing so we need following settings on web.config file.
    1. For we use large images for resizing so we need following settings
    2. For we use large images for resizing so we need following settings
    3. Sometimes we face an issue with garbage collection and memory when we upload large size of images so we use the following things to remove garbage collection and other space.

GC.Collect();
GC.WaitForPendingFinalizers();
  1. Currently, I was store resized image in a folder so first create one folder in our solution where we need to store resized images.
    Note:- In this article, we store resized images on our server but if we need to store resized images on the cloud then please refer to my next article “ Upload Multiple Images In Azure Blob Storage ”.
     was store resized image
  2. Create Action in Controller where we call the “ResizeImage()” function.

Also Read: Uploading Multiple Images to Azure Blob Storage: A Step-by-Step Guide


public ActionResult UploadImageThumb(HttpPostedFileBase fileToUpload)
{
	string myfile = ResizeImage(fileToUpload);
	return RedirectToAction("Index", new { imgName = myfile });
}

public ActionResult Index(string imgName)
{
	ViewBag.ImgName = imgName;
	return View();
}

Example:

GIF showing ASP.NET image upload demo with ShareX hotkeys configuration window for screen capture and recording
The source code shown in this article can be downloaded from here:

https://github.com/prajapatichintan/Resize-Large-Image-With-Good-Quality

How This C# Image Resize Logic Works

The resizing process shown above follows several important steps to maintain image quality and prevent image distortion.
  • The uploaded image is loaded into memory using the Image class.
  • The application calculates new dimensions based on the original aspect ratio.
  • A new bitmap is created using the calculated dimensions.
  • High-quality graphics settings are applied to improve the final output.
  • The image is redrawn at the new size using bicubic interpolation.
  • The resized image is saved as a JPEG file.
This approach helps preserve image clarity while reducing file dimensions and storage requirements.

Resize Bitmap in C#

Bitmap resizing is another common requirement in .NET applications.

A bitmap image can be resized by creating a new bitmap object with the desired dimensions and drawing the original image onto the new canvas.

When resizing bitmap images, developers should consider:

  • Maintaining aspect ratio
  • Selecting appropriate interpolation modes
  • Preventing image stretching
  • Preserving visual quality
  • Managing memory consumption efficiently
Using high-quality interpolation settings helps produce smoother results compared to default image scaling methods.

C# PictureBox Resize Image

Windows Forms applications frequently use the PictureBox control to display images.

Instead of modifying the original image dimensions, developers can resize the displayed image by adjusting the PictureBox properties.

Common PictureBox sizing options include:

Size ModeDescription
NormalDisplays image at original size
StretchImageStretches image to fit control
AutoSizeAutomatically adjusts control size
CenterImageCenters image inside control
ZoomPreserves aspect ratio while fitting image
For most applications, the Zoom mode provides the best balance between appearance and image quality because it prevents distortion while fitting the image inside the available space.

Best Practices for Resizing Images in C#

To achieve optimal results when resizing images in C#, consider the following recommendations:

Preserve Aspect Ratio

Always calculate dimensions proportionally to avoid stretching or squashing the image.

Use High-Quality Interpolation

High-quality bicubic interpolation generally produces smoother and sharper resized images.

Resize Before Storage

Reducing image dimensions before saving files helps minimize storage usage and upload times.

Create Multiple Image Sizes

Generating thumbnail, medium, and full-size versions can improve application performance and user experience.

Dispose Graphics Resources Properly

Releasing image and graphics resources prevents memory leaks and improves application stability.

Compress Images When Appropriate

Combining resizing with image compression can significantly reduce file size while maintaining acceptable visual quality.

FAQ

How do I resize an image in C#?

You can resize an image in C# by loading the image, calculating new dimensions, creating a new bitmap, and drawing the original image onto the resized canvas using high-quality graphics settings.

How can I resize an image without losing quality in C#?

To maintain image quality, preserve the aspect ratio and use high-quality interpolation settings such as HighQualityBicubic when drawing the resized image.

What is the best way to resize bitmap images in C#?

The recommended approach is to create a new bitmap with the desired dimensions and redraw the original image using high-quality rendering options.

Why should I resize images before uploading them?

Resizing images before upload reduces storage requirements, improves page load speed, decreases bandwidth usage, and enhances overall application performance.

How do I maintain aspect ratio while resizing an image?

Aspect ratio can be preserved by calculating the new width and height proportionally based on the original image dimensions.

What image formats can be resized in C#?

C# supports resizing various image formats including JPEG, PNG, BMP, GIF, TIFF, and other commonly used image formats supported by the .NET framework.


Article by

Chintan Prajapati

Chintan Prajapati is the Founder and CEO of Satva Solutions and a seasoned computer engineer with over two decades of experience in the software industry. His expertise spans Accounting & ERP Integrations, Robotic Process Automation, and the development of technology solutions built around leading ERP and accounting platforms with a particular focus on responsible AI and machine learning in fintech.Chintan holds a BE in Computer Engineering and carries an impressive roster of certifications, including Microsoft Certified Professional, Microsoft Certified Technology Specialist, Certified Azure Solution Developer, Certified Intuit Developer, Certified QuickBooks ProAdvisor, and Xero Developer.Over the course of his career, he has made a measurable impact on the accounting industry consulting on and delivering integration and automation solutions that have collectively saved thousands of man-hours. His writing aims to offer readers practical, insight-driven advice on harnessing technology to unlock greater business efficiency.When he steps away from the desk, Chintan can be found trekking through mountain trails or watching birds in the wild. Grounded in the philosophy of delivering the highest value to clients, he continues to champion innovation and excellence in digital transformation from his home base in Ahmedabad, India.