Compress and Reduce File Size of Images in ASP.NET Core

In today's digital era, images are integral to web applications and user experiences. However, dealing with large image files can result in sluggish webpage loading and higher storage expenses. To tackle this problem, it's crucial to compress and shrink the size of uploaded images while maintaining their quality. In this article, we'll explore how to accomplish this using the ImageSharp library within an ASP.NET Core application.

Prerequisites

Before we dive into the solution, make sure you have the following:

  • Visual Studio or Visual Studio Code with ASP.NET Core development tools installed.
  • .NET Core SDK.
  • Basic knowledge of ASP.NET Core and C#.

Compress and Reduce Images File Size in ASP.NET Core

To get started, create a new ASP.NET Core Web API application or use an existing one. For this demonstration, we will create an application with name "ImageUploadWithCompress".

Step 1. Installing the ImageSharp Library

We will use the ImageSharp library to perform image compression. To install it, open your project's terminal and run the following command: Install-Package SixLabors.ImageSharp

Step 2. Create a Service for Image Compression

In your project, create a service class to handle image compression. Here's a sample service class:

using SixLabors.ImageSharp.Formats.Jpeg;

namespace ImageUploadWithCompress
{
    public class ImageService
    {
        public async Task CompressAndSaveImageAsync(IFormFile imageFile, string outputPath, int quality = 75)
        {
            using var imageStream = imageFile.OpenReadStream();
            using var image = Image.Load(imageStream);
            var encoder = new JpegEncoder
            {
                Quality = quality, // Adjust this value for desired compression quality
            };

            await Task.Run(() => image.Save(outputPath, encoder));
        }
    }
}

The above method is responsible for compressing an image represented as an IFormFile and saving the compressed image to a specified output path asynchronously.

  • (IFormFile imageFile, string outputPath, int quality = 75): These are the method's parameters.

    • IFormFile imageFile: This parameter represents the input image file that needs to be compressed. An IFormFile is typically used to handle file uploads in web applications.
    • string outputPath: This parameter specifies the path where the compressed image will be saved.
    • int quality = 75: This is an optional parameter with a default value of 75. It determines the quality of the JPEG compression. You can adjust this value to control the compression level (higher values mean better quality but larger file size, and lower values mean more compression but lower quality).

Step 3. Compress and Save Uploaded Images

Now create a controller named "ImageController" where we handle file uploads, use the ImageService class to compress and save the uploaded image while keeping the original file intact. Here's an example:

using Microsoft.AspNetCore.Mvc;

namespace ImageUploadWithCompress.Controllers
{
    [Route("api/images")]
    [ApiController]
    public class ImageController : ControllerBase
    {
        public ImageController()
        {

        }

        [HttpPost("upload")]
        public async Task<IActionResult> UploadImage(IFormFile imageFile)
        {
            if (imageFile == null || imageFile.Length == 0)
            {
                // Handle invalid input
                return BadRequest("No file uploaded");
            }

            // Save the orginal file to compress
            var outputPath = Path.Combine("uploads", imageFile.FileName);
            var imageService = new ImageService();
            await imageService.CompressAndSaveImageAsync(imageFile, outputPath, 30);

            // We can save the original file as well if needed
            var originalFilePath = Path.Combine("uploads", "original_" + imageFile.FileName);
            using (var fileStream = new FileStream(originalFilePath, FileMode.Create))
            {
                await imageFile.CopyToAsync(fileStream);
            }

            // Return success response or perform further actions
            return Ok("Image uploaded and compressed.");
        }
    }
}

Conclusion

By following these steps, you can effectively reduce the file size of uploaded images in your ASP.NET Core application without resorting to zip files. Image compression not only saves storage space but also improves the performance of your web application by reducing the load time of images. Hope this article will help users to understand How to Compress and Reduce File Size of Images. Happy Coding.