Login Register
Code2night
  • Home
  • Blog Archive
  • Learn
    • Tutorials
    • Videos
  • Interview Q&A
  • Languages
    • Angular Angular js ASP.NET Asp.net Core ASP.NET Core, C# C C# DotNet
      HTML/CSS Java JavaScript 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. C#
  4. Compress image using ImageCompress NuGet package

Compress image using ImageCompress NuGet package

Date- Jul 22,2022

Updated Jan 2026

6954

Free Download
compress images csharp compress jpeg csharp

What is Image Compression?

Image compression refers to the process of reducing the file size of an image without significantly affecting its quality. This is vital for optimizing web applications, as smaller images load faster, which improves the overall user experience. Additionally, compressed images consume less bandwidth, which is particularly beneficial for users with limited data plans or slower internet connections.

There are two main types of image compression: lossy and lossless. Lossy compression reduces file size by permanently eliminating some data, which may result in a decrease in image quality. In contrast, lossless compression reduces file size without losing any data, allowing the original image to be perfectly reconstructed. The ImageCompress NuGet package offers options for both types of compression, making it versatile for different use cases.

Prerequisites

Before you begin, ensure you have the following prerequisites:

  • A development environment set up for C# and ASP.NET.
  • Visual Studio or a similar IDE installed.
  • Basic knowledge of C# and ASP.NET MVC framework.
  • The ability to install NuGet packages.

Installing the ImageCompress NuGet Package

The first step in utilizing the ImageCompress package is to install it in your project. You can do this using the NuGet Package Manager Console or through the NuGet Package Manager GUI in Visual Studio.

Install-Package ImageCompress -Version 1.0.0

Once the package is installed, you will be ready to implement image compression in your application. The following image illustrates how to install the package via the NuGet Package Manager GUI:

Compress image using ImageCompress NuGet package

Implementing Image Compression

After installing the package, you can create an action method in your controller to handle file uploads and compress the images. The code snippet below demonstrates how to read the uploaded file, convert it into a byte array, and then call the compression method from the ImageCompress package:

[HttpPost]
public ActionResult Compression(HttpPostedFileBase file) {
    try {
        using (var mS = new MemoryStream()) {
            var targetpath = Server.MapPath("/Content/Compressed/");
            var imageName = Path.GetFileNameWithoutExtension(file.FileName) + "_Compressed" + DateTime.Now.ToString("ddMMyyyyhhmmss") + Path.GetExtension(file.FileName);
            byte[] image = new byte[file.ContentLength];
            file.InputStream.Read(image, 0, image.Length);
            CompressImage.CompressingImage(targetpath, imageName, image, 900.0f, 900.0f);
        }
    } catch (Exception ex) {
        string exc = ex.Message;
    }
    return RedirectToAction("Index");
}

In this example, we specify the target path for the compressed images and create a unique filename to avoid overwriting existing files. The CompressingImage method is invoked with parameters for the target path, image name, image byte array, and desired width and height.

Creating the Upload Form

To allow users to upload images for compression, you need to create a simple HTML form in your view. The form should include a file input for selecting images and a submit button:

@{ 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"/>
}

When the form is submitted, the selected image will be sent to the Compression action method in your controller. After processing, the user will be redirected back to the index page.

Testing the Compression

Run your application and navigate to the page with the upload form. Select a large image file and click the save button. Upon successful upload and compression, the compressed image should be saved in the specified folder, demonstrating a significant reduction in file size.

The following image shows the compressed folder with the newly saved image:

Compress image using ImageCompress NuGet package 2

Edge Cases & Gotchas

While implementing image compression, there are several edge cases and potential issues to be aware of:

  • File Size Limits: Ensure that your application can handle large files. You might need to configure the maximum file upload size in your web application's configuration settings.
  • File Format Support: The ImageCompress package supports various formats, but ensure that the uploaded files are in a compatible format. You may want to validate the file type before processing.
  • Error Handling: Implement robust error handling to manage exceptions that may occur during file reading or compression. This will improve user experience and provide informative feedback.

Performance & Best Practices

To ensure optimal performance when using the ImageCompress package, consider the following best practices:

  • Optimize Images Before Upload: Encourage users to compress their images locally before uploading, especially if they are very large.
  • Asynchronous Processing: For large files, consider implementing asynchronous processing to avoid blocking the main thread, improving responsiveness.
  • Monitor Compression Quality: Test different compression settings to find the best balance between size reduction and image quality. The parameters used in the CompressingImage method can be adjusted based on your requirements.
  • Cache Compressed Images: If the same images are frequently uploaded, consider caching the compressed versions to speed up subsequent requests.

Conclusion

In this tutorial, we explored how to compress images using the ImageCompress NuGet package in an ASP.NET application. By following the steps outlined, you can effectively reduce image file sizes, enhancing your application's performance and user experience.

Key Takeaways:

  • Image compression is essential for optimizing web performance.
  • The ImageCompress NuGet package provides an easy way to compress images in various formats.
  • Implementing error handling and validation is crucial for a robust application.
  • Adopting best practices can significantly enhance the effectiveness of image compression.

With these techniques, you can ensure that your applications handle images efficiently, providing a faster and more responsive experience for your users.

Compress image using ImageCompress NuGet package 3Compress image using ImageCompress NuGet package 4

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

Related Articles

Linkedin Sign In using LinkedinLogin Nuget package in Asp-Net MVC
Apr 14, 2023
Get Channel Videos using YouTube Data Api in Asp.Net
Apr 13, 2023
How to implement Paypal in Asp.Net Core
Oct 30, 2022
Excel Export in Asp.Net MVC using XlWorkbook
Jun 11, 2022
Previous in C#
Convert HTML String To Image In C#
Next in C#
Complete Guide to C# Collections with Examples and Tips

Comments

On this page

🎯

Interview Prep

Ace your C# interview with curated Q&As for all levels.

View C# Interview Q&As

More in C#

  • Zoom C# Wrapper Integration 12905 views
  • Convert HTML String To Image In C# 11468 views
  • The report definition is not valid or is not supported by th… 10817 views
  • Replacing Accent Characters with Alphabet Characters in CSha… 9784 views
  • Get IP address using c# 8633 views
View all C# 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#
  • C
  • C#
  • DotNet
  • HTML/CSS
  • Java
  • JavaScript
  • 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