skip to Main Content

Is there any free and reliable way to compress image files (.jpg/.png) and also create thumbnails in ASP.NET Core 3.1 MVC?

I tried Bitmap’s functions but they throw exceptions like ‘System.Drawing.Common is not supported on this platform’.

2

Answers


  1. Yes, there are free and reliable ways to compress image files and create thumbnails in ASP.NET Core without using the System.Drawing.Common library, which is not supported in ASP.NET Core due to platform limitations. Here are two popular and widely used libraries that you can use:

    ImageSharp (SixLabors.ImageSharp):
    ImageSharp is a cross-platform, high-performance image processing library for .NET that can be used in ASP.NET Core applications. It provides a rich set of features for image manipulation, including resizing, cropping, compression, and more.
    To use ImageSharp in your ASP.NET Core 3.1 MVC application, you need to install the SixLabors.ImageSharp.Web NuGet package.

    Install-Package SixLabors.ImageSharp.Web

    Here’s a sample code snippet to compress an image and generate a thumbnail using ImageSharp:

    using SixLabors.ImageSharp;
    using SixLabors.ImageSharp.Processing;
    
    public void ProcessImage(string inputFilePath, string outputFilePath, int maxWidth, int maxHeight)
    {
        using (var image = Image.Load(inputFilePath))
        {
            // Resize the image to create a thumbnail
            image.Mutate(x => x.Resize(maxWidth, maxHeight));
    
            // Compress the image with the specified quality level (e.g., 70)
            var encoder = new SixLabors.ImageSharp.Formats.Jpeg.JpegEncoder { Quality = 70 };
    
            // Save the thumbnail to the output file
            image.Save(outputFilePath, encoder);
        }
    }
    
    Login or Signup to reply.
    1. Install System.Drawing.Common package.
    2. Add namespaces: System.Drawing and System.Drawing.Imaging.
    3. Implement CompressImage method to compress image using JPEG encoder with specified quality.
    4. Call CompressImage with image byte array and desired quality to get the compressed image as a byte array.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search