Cloudinary Blog

Optimizing Animated GIFs With Lossy Compression

How to Optimize Animated GIFs With Lossy Compression

Even though the image format animated GIFs are gaining popularity, their file size is usually large, causing slow loading and incurring high bandwidth costs. Besides, the GIF format is old and not optimized for modern video clips. The developer’s job of effecting fast loading of animated GIFs and delivering optimized images is complex and time-consuming.

Converting Animated GIFs to Videos or Animated WebP Files: The Caveats

With Cloudinary, you can convert animated GIFs to videos, reducing the file size and saving bandwidth (see this post for more details). However, videos are much harder to embed in websites and apps than regular images, let alone that auto-playing of videos does not work in some browsers and mobile devices. Alternatively, you can convert animated GIFs to animated WebP files. Unfortunately, the WebP format, which, being developed by Google, works only on Chrome, Android, and Opera, but not on most of the other popular mobile devices and browsers.

Furthermore, GIF conversion tools tend to produce either large, high visual-quality files or small, low visual-quality ones, neither of which lives up to optimization standards.

Understanding Lossy Compression

When lossy compression starts, filtering occurs, eliminating certain pixel data through an increase of redundant patterns along scan lines. In reality, the term lossy compression is a misnomer for GIFs, whose format is palette based, because the related compression algorithms are lossless, hence no data loss in the output.

Note
Because of the 8-bit GIF limit of 256 colors, converting other image formats to GIF does result in data loss.

As reference, read this section in the Cloudinary documentation on image optimization: the whys, the whats, and the tools.

Applying Lossy Compression to Animated GIFs

Optimizing animated GIFs with a lossy-compression technique yields smaller yet visually appealing images, a win-win. With Cloudinary, you apply lossy compression through the platform’s on-the-fly, dynamic URLs with no need for any software or additional computational power. Why? Because the compression process takes place in the cloud.

All you need to do is set the flag parameter to lossy (fl_lossy in URLs). For example, this animated GIF named kitten_fighting, already uploaded to Cloudinary, is 6.3 MB in size.

Ruby:
Copy to clipboard
cl_image_tag("kitten_fighting.gif")
PHP v1:
Copy to clipboard
cl_image_tag("kitten_fighting.gif")
PHP v2:
Copy to clipboard
(new ImageTag('kitten_fighting.gif'));
Python:
Copy to clipboard
CloudinaryImage("kitten_fighting.gif").image()
Node.js:
Copy to clipboard
cloudinary.image("kitten_fighting.gif")
Java:
Copy to clipboard
cloudinary.url().imageTag("kitten_fighting.gif");
JS:
Copy to clipboard
cloudinary.imageTag('kitten_fighting.gif').toHtml();
jQuery:
Copy to clipboard
$.cloudinary.image("kitten_fighting.gif")
React:
Copy to clipboard
<Image publicId="kitten_fighting.gif" >

</Image>
Vue.js:
Copy to clipboard
<cld-image publicId="kitten_fighting.gif" >

</cld-image>
Angular:
Copy to clipboard
<cl-image public-id="kitten_fighting.gif" >

</cl-image>
.NET:
Copy to clipboard
cloudinary.Api.UrlImgUp.BuildImageTag("kitten_fighting.gif")
Android:
Copy to clipboard
MediaManager.get().url().generate("kitten_fighting.gif");
iOS:
Copy to clipboard
imageView.cldSetImage(cloudinary.createUrl().generate("kitten_fighting.gif")!, cloudinary: cloudinary)
original non-optimized animated GIF

Adding the fl_lossy parameter to the delivery URL reduces that size by 40 percent to 2.5 MB. The optimized GIF, as shown below, looks just as sharp as the original.

Ruby:
Copy to clipboard
cl_image_tag("kitten_fighting.gif", :flags=>"lossy")
PHP v1:
Copy to clipboard
cl_image_tag("kitten_fighting.gif", array("flags"=>"lossy"))
PHP v2:
Copy to clipboard
(new ImageTag('kitten_fighting.gif'))
  ->delivery(Delivery::format(Format::gif())
    ->lossy());
Python:
Copy to clipboard
CloudinaryImage("kitten_fighting.gif").image(flags="lossy")
Node.js:
Copy to clipboard
cloudinary.image("kitten_fighting.gif", {flags: "lossy"})
Java:
Copy to clipboard
cloudinary.url().transformation(new Transformation().flags("lossy")).imageTag("kitten_fighting.gif");
JS:
Copy to clipboard
cloudinary.imageTag('kitten_fighting.gif', {flags: "lossy"}).toHtml();
jQuery:
Copy to clipboard
$.cloudinary.image("kitten_fighting.gif", {flags: "lossy"})
React:
Copy to clipboard
<Image publicId="kitten_fighting.gif" >
  <Transformation flags="lossy" />
</Image>
Vue.js:
Copy to clipboard
<cld-image publicId="kitten_fighting.gif" >
  <cld-transformation flags="lossy" />
</cld-image>
Angular:
Copy to clipboard
<cl-image public-id="kitten_fighting.gif" >
  <cl-transformation flags="lossy">
  </cl-transformation>
</cl-image>
.NET:
Copy to clipboard
cloudinary.Api.UrlImgUp.Transform(new Transformation().Flags("lossy")).BuildImageTag("kitten_fighting.gif")
Android:
Copy to clipboard
MediaManager.get().url().transformation(new Transformation().flags("lossy")).generate("kitten_fighting.gif");
iOS:
Copy to clipboard
imageView.cldSetImage(cloudinary.createUrl().setTransformation(CLDTransformation().setFlags("lossy")).generate("kitten_fighting.gif")!, cloudinary: cloudinary)
Optimized animated GIF with lossy compression

An excellent tip on GIF compression: to fine-tune the level of lossy compression in compressed animated GIFs, add the quality parameter (q in URLs), whose default value is 80. Enabling lossy compression and setting the quality parameter to 50 for the kitten GIF produces a 2.1-MB image, approximately 30 percent of the original size:

Ruby:
Copy to clipboard
cl_image_tag("kitten_fighting.gif", :flags=>"lossy", :quality=>50)
PHP v1:
Copy to clipboard
cl_image_tag("kitten_fighting.gif", array("flags"=>"lossy", "quality"=>50))
PHP v2:
Copy to clipboard
(new ImageTag('kitten_fighting.gif'))
  ->delivery(Delivery::format(Format::gif())
    ->lossy())
  ->delivery(Delivery::quality(50));
Python:
Copy to clipboard
CloudinaryImage("kitten_fighting.gif").image(flags="lossy", quality=50)
Node.js:
Copy to clipboard
cloudinary.image("kitten_fighting.gif", {flags: "lossy", quality: 50})
Java:
Copy to clipboard
cloudinary.url().transformation(new Transformation().flags("lossy").quality(50)).imageTag("kitten_fighting.gif");
JS:
Copy to clipboard
cloudinary.imageTag('kitten_fighting.gif', {flags: "lossy", quality: 50}).toHtml();
jQuery:
Copy to clipboard
$.cloudinary.image("kitten_fighting.gif", {flags: "lossy", quality: 50})
React:
Copy to clipboard
<Image publicId="kitten_fighting.gif" >
  <Transformation flags="lossy" quality="50" />
</Image>
Vue.js:
Copy to clipboard
<cld-image publicId="kitten_fighting.gif" >
  <cld-transformation flags="lossy" quality="50" />
</cld-image>
Angular:
Copy to clipboard
<cl-image public-id="kitten_fighting.gif" >
  <cl-transformation flags="lossy" quality="50">
  </cl-transformation>
</cl-image>
.NET:
Copy to clipboard
cloudinary.Api.UrlImgUp.Transform(new Transformation().Flags("lossy").Quality(50)).BuildImageTag("kitten_fighting.gif")
Android:
Copy to clipboard
MediaManager.get().url().transformation(new Transformation().flags("lossy").quality(50)).generate("kitten_fighting.gif");
iOS:
Copy to clipboard
imageView.cldSetImage(cloudinary.createUrl().setTransformation(CLDTransformation().setFlags("lossy").setQuality(50)).generate("kitten_fighting.gif")!, cloudinary: cloudinary)
50-percent quality lossy animated GIF

Further Transforming Animated GIFs

You can apply lossy compression on Cloudinary with any of the platform’s rich set of image optimization and transformation capabilities to match any graphic design, dimension, device, browser, responsive layout, and such. Lossy compression can also optimize generated images. So, instead of optimizing the original, large animated GIF, you can optimize a transformed or cropped version for display.

For example, these steps generate and deliver a calibrated version of the kitten GIF:

  1. Crop the GIF to a width of 50 percent and a height of 80 percent.
  2. Add an uploaded PNG image named cloudinary_icon as an overlay. Resize the overlay to a width of 40 pixels, positioned 5 pixels from the top-right corner of the animated GIF; and make the overlay 40 percent semitransparent.
  3. Apply lossy compression with a quantity value of 50 percent.

Voila! The optimized GIF size is only 765 KB, 60 percent less than the original size of 1.9 MB.

Ruby:
Copy to clipboard
cl_image_tag("kitten_fighting.gif", :transformation=>[
  {:width=>0.5, :height=>0.8, :crop=>"crop"},
  {:overlay=>"cloudinary_icon", :width=>40, :gravity=>"north_east", :opacity=>40, :x=>5, :y=>5, :crop=>"scale"},
  {:flags=>"lossy", :quality=>50}
  ])
PHP v1:
Copy to clipboard
cl_image_tag("kitten_fighting.gif", array("transformation"=>array(
  array("width"=>"0.5", "height"=>"0.8", "crop"=>"crop"),
  array("overlay"=>"cloudinary_icon", "width"=>40, "gravity"=>"north_east", "opacity"=>40, "x"=>5, "y"=>5, "crop"=>"scale"),
  array("flags"=>"lossy", "quality"=>50)
  )))
PHP v2:
Copy to clipboard
(new ImageTag('kitten_fighting.gif'))
  ->resize(Resize::crop()->width(0.5)->height(0.8))
  ->overlay(
      Overlay::source(Source::image('cloudinary_icon')
        ->transformation((new ImageTransformation())
          ->resize(Resize::scale()->width(40))
          ->adjust(Adjust::opacity(40))))
      ->position((new Position())
        ->gravity(Gravity::compass(Compass::northEast()))
        ->offsetX(5)->offsetY(5)))
    ->delivery(Delivery::format(Format::gif())
      ->lossy())
    ->delivery(Delivery::quality(50));
Python:
Copy to clipboard
CloudinaryImage("kitten_fighting.gif").image(transformation=[
  {'width': "0.5", 'height': "0.8", 'crop': "crop"},
  {'overlay': "cloudinary_icon", 'width': 40, 'gravity': "north_east", 'opacity': 40, 'x': 5, 'y': 5, 'crop': "scale"},
  {'flags': "lossy", 'quality': 50}
  ])
Node.js:
Copy to clipboard
cloudinary.image("kitten_fighting.gif", {transformation: [
  {width: "0.5", height: "0.8", crop: "crop"},
  {overlay: "cloudinary_icon", width: 40, gravity: "north_east", opacity: 40, x: 5, y: 5, crop: "scale"},
  {flags: "lossy", quality: 50}
  ]})
Java:
Copy to clipboard
cloudinary.url().transformation(new Transformation()
  .width(0.5).height(0.8).crop("crop").chain()
  .overlay(new Layer().publicId("cloudinary_icon")).width(40).gravity("north_east").opacity(40).x(5).y(5).crop("scale").chain()
  .flags("lossy").quality(50)).imageTag("kitten_fighting.gif");
JS:
Copy to clipboard
cloudinary.imageTag('kitten_fighting.gif', {transformation: [
  {width: "0.5", height: "0.8", crop: "crop"},
  {overlay: new cloudinary.Layer().publicId("cloudinary_icon"), width: 40, gravity: "north_east", opacity: 40, x: 5, y: 5, crop: "scale"},
  {flags: "lossy", quality: 50}
  ]}).toHtml();
jQuery:
Copy to clipboard
$.cloudinary.image("kitten_fighting.gif", {transformation: [
  {width: "0.5", height: "0.8", crop: "crop"},
  {overlay: new cloudinary.Layer().publicId("cloudinary_icon"), width: 40, gravity: "north_east", opacity: 40, x: 5, y: 5, crop: "scale"},
  {flags: "lossy", quality: 50}
  ]})
React:
Copy to clipboard
<Image publicId="kitten_fighting.gif" >
  <Transformation width="0.5" height="0.8" crop="crop" />
  <Transformation overlay="cloudinary_icon" width="40" gravity="north_east" opacity="40" x="5" y="5" crop="scale" />
  <Transformation flags="lossy" quality="50" />
</Image>
Vue.js:
Copy to clipboard
<cld-image publicId="kitten_fighting.gif" >
  <cld-transformation width="0.5" height="0.8" crop="crop" />
  <cld-transformation :overlay="cloudinary_icon" width="40" gravity="north_east" opacity="40" x="5" y="5" crop="scale" />
  <cld-transformation flags="lossy" quality="50" />
</cld-image>
Angular:
Copy to clipboard
<cl-image public-id="kitten_fighting.gif" >
  <cl-transformation width="0.5" height="0.8" crop="crop">
  </cl-transformation>
  <cl-transformation overlay="cloudinary_icon" width="40" gravity="north_east" opacity="40" x="5" y="5" crop="scale">
  </cl-transformation>
  <cl-transformation flags="lossy" quality="50">
  </cl-transformation>
</cl-image>
.NET:
Copy to clipboard
cloudinary.Api.UrlImgUp.Transform(new Transformation()
  .Width(0.5).Height(0.8).Crop("crop").Chain()
  .Overlay(new Layer().PublicId("cloudinary_icon")).Width(40).Gravity("north_east").Opacity(40).X(5).Y(5).Crop("scale").Chain()
  .Flags("lossy").Quality(50)).BuildImageTag("kitten_fighting.gif")
Android:
Copy to clipboard
MediaManager.get().url().transformation(new Transformation()
  .width(0.5).height(0.8).crop("crop").chain()
  .overlay(new Layer().publicId("cloudinary_icon")).width(40).gravity("north_east").opacity(40).x(5).y(5).crop("scale").chain()
  .flags("lossy").quality(50)).generate("kitten_fighting.gif");
iOS:
Copy to clipboard
imageView.cldSetImage(cloudinary.createUrl().setTransformation(CLDTransformation()
  .setWidth(0.5).setHeight(0.8).setCrop("crop").chain()
  .setOverlay("cloudinary_icon").setWidth(40).setGravity("north_east").setOpacity(40).setX(5).setY(5).setCrop("scale").chain()
  .setFlags("lossy").setQuality(50)).generate("kitten_fighting.gif")!, cloudinary: cloudinary)
Animated GIF resized, with overlay added and 50-percent lossy GIF compression

Summing Up

To recap, applying lossy compression to animated GIFs yields two major benefits: the flexibility of displaying those lively GIFs and the bandwidth savings from smaller yet still-visually-pleasing images, not to mention an enhanced user experience. The setup takes only minimal effort on your part, freeing you up to focus on developing websites and apps.

Keep in mind these two handy tips:

Lossy compression for animated GIFs is available in all of Cloudinary’s free and paid plans. To give it a try, sign up for a free account and forge ahead. You’ll likely be impressed.

Want to Learn More About Image Formats?

Recent Blog Posts

Our $2B Valuation

By
Blackstone Growth Invests in Cloudinary

When we started our journey in 2012, we were looking to improve our lives as developers by making it easier for us to handle the arduous tasks of handling images and videos in our code. That initial line of developer code has evolved into a full suite of media experience solutions driven by a mission that gradually revealed itself over the course of the past 10 years: help companies unleash the full potential of their media to create the most engaging visual experiences.

Read more
Direct-to-Consumer E-Commerce Requires Compelling Visual Experiences

When brands like you adopt a direct–to-consumer (DTC) e-commerce approach with no involvement of retailers or marketplaces, you gain direct and timely insight into evolving shopping behaviors. Accordingly, you can accommodate shoppers’ preferences by continually adjusting your product offering and interspersing the shopping journey with moments of excitement and intrigue. Opportunities abound for you to cultivate engaging customer relationships.

Read more
Automatically Translating Videos for an International Audience

No matter your business focus—public service, B2B integration, recruitment—multimedia, in particular video, is remarkably effective in communicating with the audience. Before, making video accessible to diverse viewers involved tasks galore, such as eliciting the service of production studios to manually dub, transcribe, and add subtitles. Those operations were costly and slow, especially for globally destined content.

Read more
Cloudinary Helps Minted Manage Its Image-Generation Pipeline at Scale

Shoppers return time and again to Minted’s global online community of independent artists and designers because they know they can count on unique, statement-making products of the highest quality there. Concurrently, the visual imagery on Minted.com must do justice to the designs into which the creators have poured their hearts and souls. For Minted’s VP of Engineering David Lien, “Because we are a premium brand, we need to ensure that every single one of our product images matches the selected configuration exactly. For example, if you pick an 18x24 art print on blue canvas, we will show that exact combination on the hero images in the PDF.”

Read more
Highlights on ImageCon 2021 and a Preview of ImageCon 2022

New year, same trend! Visual media will continue to play a monumental role in driving online conversions. To keep up with visual-experience trends and best practices, Cloudinary holds an annual conference called ImageCon, a one-of-a-kind event that helps attendees create the most engaging visual experiences possible.

Read more