Web Performance How Image Encoding Works Exploring Video Hosting The Art of Compromise: How Lossy Compression Works Understanding the ‘Image Loading Error’: Comprehensive Guide A Comprehensive Guide to Resizing Images on iOS VBR vs CBR: Understanding Bitrate for Optimal Media Handling Displaying Images with Python’s Top 5 Image Libraries 4 Ways to Add Images to GitHub README + 1 Bonus Method Converting Images with Python JavaScript Image Optimization Techniques Building an Image Picker in React with react-native-image-crop-picker 6 Ways to Save Images in Python 5 Ways to Import Images in React + Bonus Automation Method Extract Text from Images in Python with Pillow and pytesseract Downloading Image from URL in Python: 5 Ways with Code Examples Image.open Python Function: Syntax and Quick Tutorial Complete Guide to Video SEO & Automating It With Cloudinary A Complete Guide To Website Image Optimization Video Encoding: How It Works, Formats & Best Practices The Developer’s Guide to PDFs Integrating Cloudinary With Gatsby For Image Optimization Mastering Image Optimization With Netlify And Cloudinary Seamlessly Integrate Cloudinary With Netlify For Optimised Website Assets Ultimate Guide to Asset Optimization Using Cloudinary and Netlify Adding Video To Magento Understanding Magento Media Adding a Video Widget to Your Website: What You Need to Know SDR vs. HDR: Differences and 5 Considerations for Content Creators Audio Manipulation In PHP Image Management Systems: Key Capabilities and Best Practices Video CDN: Why You Need It and Top 5 Video CDNs Video Optimization: Why You Need It and 5 Critical Best Practices Multi CDN: 8 Amazing Benefits, Methods, and Best Practices What Is an Optimized Website and 6 Ways to Optimize Yours Understanding Image Hosting for Websites Sprite Generation with CSS and 4 Automated Tools 8 Image SEO Optimization Tips to Improve Your Search Rankings Website Speed: 5 Reasons Your Site is Slow and How to Fix It Web Performance: What is it, Trends and Insights for 2024

The Art of Compromise: How Lossy Compression Works

lossy compression

With the ever-increasing data generated worldwide, compressing digital assets for efficient delivery is a common practice almost anywhere. Digital assets like images and videos are compressed and optimized for various purposes, including file type changes, dimension editing, cropping, bit depth reduction, and more.

Image compression is especially important for images used on websites and applications, where loading speed and storage efficiency are critical. In this article, we’ll explore different tools for achieving lossy compression, a type of image compression technique, in Python using Cloudinary.

In this article:

Lossy vs Lossless Image Compression

Lossy compression is a type of image optimization technique that reduces the file size of an image by permanently removing unnecessary information and details from the image. Some common examples of lossy compression image formats include JPEG, HEIC, WebP, glTF, JPEG 2000, and TIFF.

On the other hand, lossless image compression is an optimization technique that reduces the size of an image file without sacrificing any significant information or diminishing its quality. Lossless image compression works by removing unnecessary metadata or redundancy and reconstructing the information more efficiently. Examples of lossless compressed image file formats include PNG, BMP, and GIF.

lossy compression

Advantages and Disadvantages of Lossy Image Comprehension

Despite its popularity and wide adoption, lossy compression has its advantages and disadvantages. Knowing these can help you make an informed decision when compressing images for various use cases. Let’s go through some of them.

The Advantages of Lossy Image Compression

  • Storage Saving. Since lossy compressed images have a smaller file size, they take up less storage space. This is a great advantage, especially for devices with limited storage capacity and for reducing cloud storage and data transmission costs.
  • Faster Loading Images. Lossy images load considerably faster due to their relatively small file size (often by a 50-90% reduction of the original size) than lossless or uncompressed images. This can significantly impact users’ experience, as visitors to websites and applications do not have to wait long for images to load.
  • Better SEO. Search engines favor websites with faster loading times, as this improves user experience. Lossy compressed images load faster, and websites that utilize them often achieve better SEO rankings.
  • Widely Supported. Lossy image formats, such as JPEG and WebP, are widely supported across various platforms, browsers, and devices, meaning most users can view them without issues.

The Disadvantages of Lossy Compression

  • Lossy Compression is Irreversible. When an image is compressed using a lossy compression algorithm, restoring the original image quality is impossible.
  • Color Banding. Color banding is the appearance of distinct, visible bands of color in what should be smooth gradients. It may occur in areas of an image where the color transitions gradually, such as skies and shadows, resulting in posterization and loss of detail.
  • It’s Not Suitable for All Image Types. Lossy compression works poorly for images with text, sharp edges, or intricate patterns due to the production of artifacts. This makes it a poor choice for graphics, logos, or professional images that require precise color reproduction and sharp, clean lines.

lossy compression

Tools for Lossy Image Compression

Numerous tools are available for lossy image compression, depending on your use case and skill level. Let’s take a look at some of the most common ones.

Browser-based

This category of tools is easy to use, with no installation required, and accessible from any device with a web browser. They are ideal for quick one-off file compression and offer basic interfaces that allow you to configure the compression process’s settings. However, these tools are also limited by scale–they’re usually only able to handle one file at a time or in small batches.

Software

These installable applications often provide more robust functionality and advanced features and control. They offer additional editing capabilities and are suitable for professional use and complex workflows but are usually tied to other functionalities, such as image editors or file converters. Some examples of these include Adobe Photoshop, GIMP, and ImageOptim.

Command Line Tools

If you’re more experienced and comfortable with writing complex scripts for automation and bulk processing of images, then you may want to consider this option. Far more advanced than regular software–and equally complex–these tools can offer much more flexibility and customization for lossy compression. However, they often have a steep learning curve if you’re not already familiar with the command line. Notable examples include ImageMagick, Pillow, and pngquant.

Libraries and packages

This option is ideal if you have programming language skills and want to integrate lossy compression into your software projects. With this method, you can programmatically control compression settings and modify them to your liking, build custom image processing pipelines, etc. Various libraries and packages are available for programming languages, such as Sharp for Node.js, Pillow for Python, ImageProcessor for C#, and many others.

Lossy Compress Images with Cloudinary

Image optimization is one of Cloudinary’s core features. Cloudinary allows you to optimize images by delivering them in different formats, dimensions, quality, or resolutions. One major advantage of Cloudinary over other libraries and packages is that it can be used in several popular programming languages through one of its many SDKs.

Cloudinary uses a robust and efficient algorithm to automatically deliver images of the highest optimal quality to your users when delivering your uploaded images. By default, Cloudinary compresses images using an optimal encoder to return a compressed image based on your use case or the end user’s device.

To use lossy compression with images in Cloudinary, we can use the lossy flag (or fl_lossy in URLs) in the transformation parameters of the image asset.

Let’s take the following image with a file size of ~480 KB, for example:

<https://res.cloudinary.com/demo/image/upload/cld-sample.jpg>

lossy compression

Now, adding the fl_lossy flag to the URL reduces the image to about ~420 KB:

<https://res.cloudinary.com/demo/image/upload/fl_lossy/cld-sample.jpg>

lossy compression

That’s about a 13% reduction in size.

But… We can get a better result.

Adding the q_auto and fl_lossy flags together will make Cloudinary use its built-in intelligent quality selection algorithm to compress the image to a smaller file size while still maintaining an acceptable quality.

Here’s the image with a size of ~245 KB. That’s a whooping ~49% reduction in file size!

<https://res.cloudinary.com/demo/image/upload/q_auto,fl_lossy/cld-sample.jpg>

lossy compression

Comparing this image with the original, you can tell it’ll take a lot of efforts to spot any differences between the two. This example highlights Cloudinary’s state-of-the-art compression algorithm, with which you can compress images more efficiently, while maintaining a level of quality that is virtually indistinguishable from the original to the human eye.

Wrapping Up

Lossy image compression is an optimization technique widely used in digital media, including images, video, and audio, to improve performance or achieve a specific goal. So far, we have explored what lossy compression entails and discussed its advantages and disadvantages. This comprehensive overview equips you with the knowledge to make informed decisions when compressing images for various applications.

Take your digital experience to the next level with Cloudinary’s powerful media optimization tools. Sign up for free today!

QUICK TIPS
Tamas Piros
Cloudinary Logo Tamas Piros

In my experience, here are tips that can help you better optimize and manage lossy compression in your workflows:

  1. Use perceptual quality metrics
    Incorporate perceptual quality metrics, such as SSIM (Structural Similarity Index) or PSNR (Peak Signal-to-Noise Ratio), to evaluate compression effectiveness. These metrics provide a better measure of how compression impacts human visual perception, allowing you to fine-tune the balance between file size reduction and image quality.
  2. Batch process with adaptive algorithms
    When processing large batches of images, use adaptive algorithms that automatically adjust compression levels based on the content of each image. This approach ensures that simpler images receive more aggressive compression, while complex images retain necessary details.
  3. Optimize for specific use cases
    Tailor your compression strategies to the specific use case. For example, if images are intended for social media, prioritize speed and lower file sizes. For e-commerce, focus on preserving product detail to ensure high visual quality that can impact purchasing decisions.
  4. Implement progressive JPEGs for better UX
    Use progressive JPEGs for web images, which load in layers, displaying a low-quality version first before gradually improving as the image fully loads. This provides a better user experience on slower connections by showing content faster, even if the final image isn’t yet fully rendered.
  5. Apply region-based compression
    For images with critical focal points, such as faces or text, apply region-based compression techniques. This method compresses less important areas more heavily while preserving the quality of key regions, ensuring that important details remain sharp.
  6. Integrate with automated content delivery
    Combine lossy compression with automated content delivery networks (CDNs) that adjust image delivery based on user location, device, and network conditions. This setup optimizes performance and load times globally without manual intervention.
  7. Test across different devices and screens
    After compression, test your images across various devices and screen types, including high-DPI displays. Different screens can highlight compression artifacts differently, so testing ensures consistent quality and performance across all user scenarios.
  8. Monitor user interaction and feedback
    Use analytics to monitor how users interact with compressed images. If you notice higher bounce rates or reduced engagement, it might indicate over-compression, and adjustments may be needed to maintain a balance between performance and visual quality.
  9. Leverage AI-driven compression tools
    Implement AI-driven tools that learn and adapt compression techniques based on past results. These tools can optimize future compressions more effectively by considering user behavior, device capabilities, and the type of content being delivered.
  10. Combine with vector graphics where possible
    For images that contain sharp lines or text, consider using or combining with vector graphics (SVGs) when possible. Vectors do not lose quality with scaling and can complement raster images in scenarios where clarity is crucial, reducing reliance on lossy compression.

These tips will help you achieve efficient, high-quality results when using lossy compression, whether for web performance, storage savings, or specific business needs.

Last updated: Sep 7, 2024