Cloudinary Blog
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.


Sign up for Cloudinary free today!


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 Manipulating Animated GIFs

You can apply lossy compression on Cloudinary with any of the platform’s rich set of image optimization and manipulation 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 manipulated 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

The Benefits of Headless DAMs

Headless is not a buzzword anymore. In fact, the concept of headless architecture is gaining momentum due to the flexibility it offers for composing new experiences and for tackling the undue complexity of an ever-evolving technology stack. That’s because while the evolution of the martech landscape has enabled disruptive, digital innovations, the approach of buying point solutions for solving specific challenges can expose companies to the complicated nature of new technologies, systems, and platforms.

Read more

Building Display Ads With Transparent Video

By Afzaal Ahmad Zeeshan
Build Web Ads With Transparent Video to Attract User Engagement

Billions of views on the Internet every day drive one of the biggest industries on the planet: advertising. The sheer size of that market and the competitive nature of vying for consumer attention results in a constant need for innovation. Readers are jaded, and display ads are blind spots.

Read more
How Cloudinary's Media Optimizer Helps E-Businesses Deliver Superior Web Performance

As a technology company, Cloudinary owes its success to its ability to build solutions that address the most critical challenges you, our customers, face. The companies we serve run the gamut of digital businesses—retailers and direct-to-consumer brands, media and entertainment, travel and hospitality—which, coincidentally, all care about the same things.

Read more
How to Auto-Tag Video With Markers on Cloudinary for Easy Navigation

A picture is worth a thousand words, and that also holds true for video, one minute of which, according to Dr. James McQuivey of Forrester Research, is worth 1.8 million words. That's why online stores rely on rich media to promote products and sales. Images and videos impart a real sense of involvement with a purchase—a car, a vacation getaway, an apartment rental—setting your business apart from the competition.

Read more