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

Nowadays we need to store images in the cloud and then show them in many places like if create an E-commerce website then image galleries can be an effective method of communicating with the visitor. But if we upload large-size images then its increases the cost of storage and takes time to load on the browser so A nice compromise to this situation is to present images as thumbnails. This article shows how to Resize a large image with good quality.

Follow these simple steps:

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:

Example

The source code shown in this article can be downloaded from here:

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

Article by

Chintan Prajapati

Chintan Prajapati, a seasoned computer engineer with over 20 years in the software industry, is the Founder and CEO of Satva Solutions. His expertise lies in Accounting & ERP Integrations, RPA, and developing technology solutions around leading ERP and accounting software, focusing on using Responsible AI and ML in fintech solutions. Chintan holds a BE in Computer Engineering and is a Microsoft Certified Professional, Microsoft Certified Technology Specialist, Certified Azure Solution Developer, Certified Intuit Developer, and Xero Developer.Throughout his career, Chintan has significantly impacted the accounting industry by consulting and delivering integrations and automation solutions that have saved thousands of man-hours. He aims to provide readers with insightful, practical advice on leveraging technology for business efficiency.Outside of his professional work, Chintan enjoys trekking and bird-watching. Guided by the philosophy, "Deliver the highest value to clients". Chintan continues to drive innovation and excellence in digital transformation strategies from his base in Ahmedabad, India.