Compressing Images in C# using Magick.NET

Compressing Images in C# using Magick.NET

Recently, I was trying to work on a jQuery datatable where the profile pictures of users were to be displayed on the table and I discovered that the images uploaded were quite heavy, ranging between 3 to 5 megabytes, that's quite large!

However, the project didn't have any provisions for using cloud-based image solutions like Cloudinary and Amazon S3, so I had to look for a NuGet package that had the capability and flexibility for image processing that suited my needs (compressing the size of the image without losing quality as I also needed the images for image matching with Amazon Rekognition services).

In my search, I came across this blog post, It's an interesting and informative read.

In the above link, I came across these really great libraries, for example:

  1. ImageSharp
  2. SkiaSharp
  3. MagicScaler

However, I had the option of choosing just one and Magick.NET, a .NET wrapper of the popular ImageMagick provided more options and flexibility for what I needed to do, plus it had better recommendations from the Microsoft dev blog.

So I created a simple class with one method for compressing images using the Magick.NET library, my intentions are to extend the class with other options as needs grow. However, I like to keep things as simple as possible.

The source image path and output path is passed through the class constructor, while the optional parameters depends on your need. Although, I discovered that lower numbers for the height and width make the output image blurry. The following code snippet can be easily integrated to your codebase on the fly without encountering any hassles.

I hope this helps someone out there as it helped me!

giphy.webp

Here's a link to the repository on github.