Image compression in .NET 6
Image compression plays a vital role in today's digital landscape, as it enables efficient storage, transmission, and display of image data. With the proliferation of high-resolution images and the increasing use of multimedia content on the internet, image compression has become essential for optimizing data usage, reducing load times, and improving the overall user experience. In the industry, image compression is widely employed in various applications, such as streaming services, social media platforms, and content delivery networks, where large volumes of images are stored and transmitted regularly. In the context of C# development, image compression can be achieved using various libraries and techniques. The provided code snippet demonstrates a practical implementation of image compression using the ImageMagick library, a popular choice among .NET developers for image processing tasks.
public string CompressFileBlob(string fileBlob)
{
var BYTES_IN_MEGABYTE = 1048576.0;
var COMPRESSION_THRESHOLD = _config.GetValue<double>("Compression:Threshold");
var IMAGE_WIDTH = _config.GetValue<int>("Compression:Width");
var IMAGE_HEIGHT = _config.GetValue<int>("Compression:Height");
var COMPRESSION_QUALITY = _config.GetValue<int>("Compression:Quality");
var data = Convert.FromBase64String(fileBlob);
var dataLength = data.Length;
var dataSize = ((4 * Math.Ceiling((double)(dataLength / 3)) * 0.5624896334383812) / BYTES_IN_MEGABYTE);
if (dataSize <= COMPRESSION_THRESHOLD)
{
return fileBlob;
}
try
{
using (var image = new MagickImage(data))
{
image.Resize(IMAGE_WIDTH, IMAGE_HEIGHT);
image.Quality = COMPRESSION_QUALITY;
var compressedData = image.ToBase64();
var compressedSize = ((4 * Math.Ceiling((double)(compressedData.Length / 3)) * 0.5624896334383812) / BYTES_IN_MEGABYTE);
if (compressedSize < dataSize)
{
return compressedData;
}
}
}
catch (MagickException)
{
// Failed to compress the image, return the original fileBlob
}
return fileBlob;