Skip to main content
Login Register
Code2night
  • Home
  • Blog Archive
  • Learn
    • Tutorials
    • Videos
  • Interview Q&A
  • Resources
    • Cheatsheets
    • Tech Comparisons
  • Languages
    • Angular Angular js ASP.NET Asp.net Core ASP.NET Core, C# ASP.NET MVC ASP.NET Web Forms C C# C#, ASP.NET Core, Dapper
      C#, ASP.NET Core, Dapper, Entity Framework DotNet General Web Development HTML, CSS HTML/CSS Java JavaScript JavaScript, HTML, CSS JavaScript, Node.js Node.js
      Python Python 3.11, Pandas, SQL Python 3.11, SQL Python 3.11, SQLAlchemy Python 3.11, SQLAlchemy, SQL Python 3.11, SQLite React Security SQL Server TypeScript
  • Post Blog
  • Tools
    • Beautifiers
      JSON Beautifier HTML Beautifier XML Beautifier CSS Beautifier JS Beautifier SQL Formatter
      Dev Utilities
      JWT Decoder Regex Tester Diff Checker Cron Explainer String Escape Hash Generator Password Generator
      Converters
      Base64 Encode/Decode URL Encoder/Decoder JSON to CSV CSV to JSON JSON to TypeScript Markdown to HTML Number Base Converter Timestamp Converter Case Converter
      Generators
      UUID / GUID Generator Lorem Ipsum QR Code Generator Meta Tag Generator
      Image Tools
      Image Converter Image Resizer Image Compressor Image to Base64 PNG to ICO Background Remover Color Picker
      Text & Content
      Word Counter PDF Editor
      SEO & Web
      SEO Analyzer URL Checker World Clock
  1. Home
  2. Blog
  3. ASP.NET MVC
  4. Image Compression in Asp.net MVC

Image Compression in Asp.net MVC

Date- Jul 16,2022 Updated Mar 2026 10793 Free Download Pay & Download
AspNet MVC C#

Image Compression Overview

Image compression is a technique used to reduce the file size of images without significantly compromising their quality. This is particularly important in web applications where fast loading times and efficient resource usage are crucial. By compressing images, developers can enhance user experience, improve website performance, and reduce bandwidth consumption. There are two main types of image compression: lossless and lossy. Lossless compression retains all the original image data, while lossy compression reduces file size by removing some data, which can affect image quality.

In ASP.NET MVC, image compression can be achieved using built-in .NET libraries without the need for external packages. This allows developers to implement image compression seamlessly as part of their image upload functionality. The following sections will detail the steps involved in implementing image compression in an ASP.NET MVC project.

Prerequisites

Before we start, ensure you have the following prerequisites:

  • A basic understanding of ASP.NET MVC framework.
  • Visual Studio installed on your machine.
  • Access to a web server or local development environment where you can run an ASP.NET MVC application.

Setting Up the Project

To begin, create a new ASP.NET MVC project in Visual Studio. Once your project is set up, create a new view that will handle the image upload. In this view, you will need to add an input field for file uploads and a submit button. Here’s a simple example of the code you need to add to your view:

@{ ViewBag.Title = "Home Page"; }
@using (Html.BeginForm("Compression", "Home", FormMethod.Post, new {@enctype="multipart/form-data" })) {
<input type="file" id="file" name="file"/>
<input type="submit" value="Save"/>
}

Adding Necessary Namespaces

Next, you need to include the necessary namespaces in your controller. These namespaces will allow you to manipulate images and handle file streams. Add the following using directives at the top of your controller:

using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;

Implementing the Compression Logic

Now we will implement the image compression logic. The following method will handle the compression of the uploaded image. It takes the target path, filename, and byte array of the image as parameters:

public static void CompressImage(string targetPath, string filename, byte[] byteArrayIn) {
try {
using (MemoryStream memStream = new MemoryStream(byteArrayIn)) {
using (var image = Image.FromStream(memStream)) {
float maxHeight = 900.0f;
float maxWidth = 900.0f;
int newWidth;
int newHeight;
Bitmap originalBMP = new Bitmap(memStream);
int originalWidth = originalBMP.Width;
int originalHeight = originalBMP.Height;
if (originalWidth > maxWidth || originalHeight > maxHeight) {
float ratioX = (float)maxWidth / (float)originalWidth;
float ratioY = (float)maxHeight / (float)originalHeight;
float ratio = Math.Min(ratioX, ratioY);
newWidth = (int)(originalWidth * ratio);
newHeight = (int)(originalHeight * ratio);
} else {
newWidth = originalWidth;
newHeight = originalHeight;
}
Bitmap bitmap1 = new Bitmap(originalBMP, newWidth, newHeight);
Graphics imgGraph = Graphics.FromImage(bitmap1);
string extension = Path.GetExtension(targetPath);
if (extension.ToLower() == ".jpg") {
imgGraph.SmoothingMode = SmoothingMode.AntiAlias;
imgGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
imgGraph.DrawImage(originalBMP, 0, 0, newWidth, newHeight);
ImageCodecInfo jpgEncoder = GetEncoder(ImageFormat.Jpeg);
EncoderParameters myEncoderParameters = new EncoderParameters(1);
EncoderParameter myEncoderParameter = new EncoderParameter(Encoder.Quality, 50L);
myEncoderParameters.Param[0] = myEncoderParameter;
bitmap1.Save(targetPath, jpgEncoder, myEncoderParameters);
} else {
imgGraph.SmoothingMode = SmoothingMode.AntiAlias;
imgGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
imgGraph.DrawImage(originalBMP, 0, 0, newWidth, newHeight);
bitmap1.Save(targetPath, originalBMP.RawFormat);
}
bitmap1.Dispose();
imgGraph.Dispose();
originalBMP.Dispose();
}
}
} catch (Exception ex) {
throw new Exception("Image compression failed: " + ex.Message);
}
}

Creating the Compression Action

Now that we have the compression logic in place, we need to create an action method in our controller that will handle the image upload and call the compression method. This action will read the uploaded file, compress it, and save it to the specified location:

[HttpPost]
public ActionResult Compression(HttpPostedFileBase file) {
if (file != null && file.ContentLength > 0) {
using (var ms = new MemoryStream()) {
var targetImagePath = Server.MapPath("/Content/Compressed/" + Path.GetFileNameWithoutExtension(file.FileName) + "_Compressed_" + DateTime.Now.ToString("ddMMyyyyhhmmss") + Path.GetExtension(file.FileName));
byte[] image = new byte[file.ContentLength];
file.InputStream.Read(image, 0, file.ContentLength);
CompressImage(targetImagePath, file.FileName, image);
}
}
return RedirectToAction("Index");
}

Edge Cases & Gotchas

When implementing image compression, it is important to consider various edge cases that may arise:

  • File Size Limits: Ensure that your application has appropriate file size limits set to prevent excessively large uploads that could cause performance issues.
  • File Format Support: Not all image formats support compression in the same way. Make sure to handle different formats appropriately and provide feedback to users if their uploads are not supported.
  • Error Handling: Implement robust error handling to manage exceptions that may occur during image processing, such as unsupported formats or memory issues.

Performance & Best Practices

To optimize the performance of your image compression implementation, consider the following best practices:

  • Asynchronous Processing: If possible, implement asynchronous file uploads to avoid blocking the main thread while images are being processed.
  • Use Caching: Cache frequently accessed images to reduce the need for repeated compression and improve load times.
  • Monitor Server Performance: Regularly monitor server performance and adjust image compression settings to maintain optimal performance levels.

Conclusion

Implementing image compression in your ASP.NET MVC applications is a vital step in enhancing performance and user experience. By following the steps outlined in this article, you can effectively manage image uploads and ensure that your server resources are utilized efficiently. Here are the key takeaways:

  • Image compression reduces file sizes, improving loading times and server performance.
  • ASP.NET MVC allows for easy implementation of image compression without third-party libraries.
  • Handling edge cases and implementing best practices is essential for robust image processing.
Image Compression in Aspnet MVCImage Compression in Aspnet MVC 2Image Compression in Aspnet MVC 3Image Compression in Aspnet MVC 4Image Compression in Aspnet MVC 5

S
Shubham Batra
Programming author at Code2Night — sharing tutorials on ASP.NET, C#, and more.
View all posts →

Related Articles

Maximum request length exceeded
Jul 18, 2022
How to export view as pdf in Asp.Net Core
Jul 05, 2022
Import Excel in Asp.net MVC using OLE DB
Jun 23, 2022
Excel Export in Asp.Net MVC using XlWorkbook
Jun 11, 2022
Previous in ASP.NET MVC
Linkedin Sign In using LinkedinLogin Nuget package in Asp-Net MVC
Next in ASP.NET MVC
Maximum request length exceeded
Buy me a pizza

Comments

🔥 Trending This Month

  • 1
    HTTP Error 500.32 Failed to load ASP NET Core runtime 6,933 views
  • 2
    Error-An error occurred while processing your request in .… 11,269 views
  • 3
    Comprehensive Guide to Error Handling in Express.js 234 views
  • 4
    ConfigurationBuilder does not contain a definition for Set… 19,458 views
  • 5
    Mastering JavaScript Error Handling with Try, Catch, and F… 160 views
  • 6
    Mastering Unconditional Statements in C: A Complete Guide … 21,491 views
  • 7
    Unable to connect to any of the specified MySQL hosts 6,225 views

On this page

🎯

Interview Prep

Ace your ASP.NET MVC interview with curated Q&As for all levels.

View ASP.NET MVC Interview Q&As

More in ASP.NET MVC

  • Implement Stripe Payment Gateway In ASP.NET 58741 views
  • Jquery Full Calender Integrated With ASP.NET 39653 views
  • Microsoft Outlook Add Appointment and Get Appointment using … 27581 views
  • How to implement JWT Token Authentication and Validate JWT T… 25283 views
  • Payumoney Integration With Asp.Net MVC 23226 views
View all ASP.NET MVC posts →

Tags

AspNet C# programming AspNet MVC c programming AspNet Core C software development tutorial MVC memory management Paypal coding coding best practices data structures programming tutorial tutorials object oriented programming Slick Slider StripeNet
Free Download for Youtube Subscribers!

First click on Subscribe Now and then subscribe the channel and come back here.
Then Click on "Verify and Download" button for download link

Subscribe Now | 1770
Download
Support Us....!

Please Subscribe to support us

Thank you for Downloading....!

Please Subscribe to support us

Continue with Downloading
Be a Member
Join Us On Whatsapp
Code2Night

A community platform for sharing programming knowledge, tutorials, and blogs. Learn, write, and grow with developers worldwide.

Panipat, Haryana, India
info@code2night.com
Quick Links
  • Home
  • Blog Archive
  • Tutorials
  • About Us
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Guest Posts
  • SEO Analyzer
Dev Tools
  • JSON Beautifier
  • HTML Beautifier
  • CSS Beautifier
  • JS Beautifier
  • SQL Formatter
  • Diff Checker
  • Regex Tester
  • Markdown to HTML
  • Word Counter
More Tools
  • Password Generator
  • QR Code Generator
  • Hash Generator
  • Base64 Encoder
  • JWT Decoder
  • UUID Generator
  • Image Converter
  • PNG to ICO
  • SEO Analyzer
By Language
  • Angular
  • Angular js
  • ASP.NET
  • Asp.net Core
  • ASP.NET Core, C#
  • ASP.NET MVC
  • ASP.NET Web Forms
  • C
  • C#
  • C#, ASP.NET Core, Dapper
  • C#, ASP.NET Core, Dapper, Entity Framework
  • DotNet
  • General Web Development
  • HTML, CSS
  • HTML/CSS
  • Java
  • JavaScript
  • JavaScript, HTML, CSS
  • JavaScript, Node.js
  • Node.js
  • Python
  • Python 3.11, Pandas, SQL
  • Python 3.11, SQL
  • Python 3.11, SQLAlchemy
  • Python 3.11, SQLAlchemy, SQL
  • Python 3.11, SQLite
  • React
  • Security
  • SQL Server
  • TypeScript
© 2026 Code2Night. All Rights Reserved.
Made with for developers  |  Privacy  ·  Terms
Translate Page
We use cookies to improve your experience and analyze site traffic. By clicking Accept, you consent to our use of cookies. Privacy Policy
Accessibility
Text size
High contrast
Grayscale
Dyslexia font
Highlight links
Pause animations
Large cursor