# Optimize animated GIF files for Image Resizer

Source: https://dev.arcxp.com/photo-center/image-resizer/optimize-animated-gif-files-for-image-resizer/

This document explains how to optimize GIF files to avoid errors and improve Image Resizer performance

Image Resizer supports animated GIF files. However, depending on image quality, number of frames, as well as encoding methods and tools, animated GIFs can result in very large files, especially in terms of pixel count and number of frames. Large files cause processing bottlenecks and timeouts in Image Resizer, which leads to failovers and errors in resizing. This guide explains GIF file limitations and calculations, and provides recommendations to optimize your GIF files and improve Image Resizer performance.

## Processing limitations and file calculations

Image Resizer takes content from Photo Center and works with the Content Delivery Network (CDN) to provide images to your customers. This content pipeline can have processing and bandwidth bottlenecks (and result in failovers) if files are too large. Current maximum limits for GIF image file processing are the following:

| Parameter                                       | Value                                                    |
| ----------------------------------------------- | -------------------------------------------------------- |
| **File size on disk**                           | 128 MB for external images 50 MB for Photo Center images |
| **Total number of pixels** (summing all frames) | 100 Mp                                                   |

Even though these limits constitute a theoretical maximum for Image Resizer to work, Arc XP does not recommend using such large GIF files. Results can be unpredictable due to timeouts in processing and bandwidth limitations.

> **Tip:**
> 
> For best performance and consistent results, keep your GIF image file below 15 MB file size on disk and below 75 Mp.

### File size on disk

The file size on disk depends on each frame’s characteristics and the level of compression used. The GIF specification uses the Lempel-Ziv-Welch (LZW) lossless compression algorithm. The compression algorithm identifies and eliminates redundancies in the image data. The degree of compression depends on the complexity and repetition within the frames. In practice, animated GIFs rarely approach the file size on disk limit before hitting the total number of pixels limit described below.

### Calculating total number of pixels

You can calculate the total number of pixels using the following formula:

**`WIDTH x HEIGHT x NUMBER OF FRAMES x 8`**

The `x 8` factor accounts for the GIF bit depth (8 bits per pixel).

### GIF size calculation examples

This section provides a couple of examples of image size calculations and how they relate to Image Resizer limitations for GIF files.

- For a GIF file that is 640 x 480 pixels and has 30 frames, the calculation is as follows:  
`640 x 480 x 30 x 8 = 73,728,000`  
In this case, the total number of pixels is 73.7 Mp, which is below the 100 Mp limit for Image Resizer. This file is processed.
- For a GIF file that is 640 x 480 pixels and has 50 frames, the calculation is as follows:  
`640 x 480 x 50 x 8 = 122,880,000`  
In this case, the total number of pixels is 122.9 Mp, which exceeds the 100 Mp limit for Image Resizer. Image Resizer fails to process the file and the CDN delivers the full size image (as failover) every time the URL is accessed. This example also shows why the `x 8` factor matters: the plain frame-by-frame product is only `640 x 480 x 50 = 15,360,000` (15.4 Mp), which looks well within the limit, but after applying the `x 8` bit-depth factor the file clearly exceeds 100 Mp.

> **Important:**
> 
> Repeated Image Resizer failovers due to exceeding GIF processing limitations impact bandwidth consumption and increase bandwidth-related costs.

## General recommendations

This section provides general recommendations when working with animated GIF files to avoid issues and errors with Image Resizer.

- **Reduce the number of frames.**  
Animated GIFs are a great way to present dynamic graphic content while keeping a small file size. You must reduce the number of frames to avoid hitting the pixel number limit for Image Resizer. As a general rule, do not substitute short video clips with GIF files. Video sequences require many frames per second to achieve natural motion (cinema uses 24 frames per second, for example). Creating GIF files from video sequences quickly ramps up the number of frames. Animated GIF files are more suitable for diagrams, simple graphics, and image sequences that do not require fluid motion. If your workflow includes converting videos to GIF files, consider [using the animated WebP format](#alternative-use-animated-webp-format) instead.
- **Reduce image resolution.**  
If you are unable to reduce the number of frames in your GIF file, reduce the width and height of the image so the total number of pixels (`WIDTH x HEIGHT x NUMBER OF FRAMES x 8`, considering all frames) does not exceed 100 Mp. In practice, keep the plain `WIDTH x HEIGHT x NUMBER OF FRAMES` product below 12.5 Mp.
- **Optimize your GIF file.**  
To reduce file size and bandwidth consumption, optimize your GIF files using one of the open-source tools suggested in [GIF image processing tools](#gif-image-processing-tools)

## GIF image processing tools

There are several applications and tools that can help you optimize your GIF files before you upload them to Photo Center. This section includes an overview of two open-source tools that run on the command line.

### ImageMagick

[ImageMagick](https://imagemagick.org/index.php) can convert, resize, transform, and compose images in many formats. When it comes to the GIF format, ImageMagick provides useful features for manipulating image dimensions:

- **Resizing (`-resize`):**  
This is the primary option for changing the dimensions of a GIF file. You can specify exact dimensions, percentages, or fit within a bounding box while preserving the aspect ratio. Example:  
Terminal window  
```bash
magick input.gif -resize 300x output_300w.gif
```
This command resizes the GIF to a specific width and adjusts the height proportionally.
- **Coalescing (`-coalesce`) and cropping (`-crop`):**  
The `-coalesce` argument expands each frame to its full canvas size. This is necessary when using the `-crop` argument on an animated GIF to reduce its pixel count and content. Example:  
Terminal window  
```bash
magick animated.gif -coalesce -crop 100x100+50+50 +adjoin output_cropped_animation.gif
```
This command uses the syntax Width x Height + X offset + Y offset. Positive offsets define the top-left corner of the crop. The `+adjoin` argument ensures that each cropped frame is assembled before being reassembled into an animation. This prevents animation artifacts.
- **Pixel Count Limit (`-resize @`):**  
Resizes an image to have a specified maximum area in pixels, preserving the aspect ratio.  
```
magick input_animation.gif -coalesce -resize 4096@ -layers Optimize output_resized_pixel_limit.gif
```
This command limits the pixel count to 4096 and includes the `-coalesce` argument to reduce animation artifacts.
- **Layer Optimization `-layers Optimize`:**  
Reapplies optimization techniques after manipulating the animated GIF to reduce file size. Example:  
```
magick -layers Optimize output_optimized.gif
```
You can use the `-layers Optimize` argument in conjunction with other arguments to ensure your GIF output file is always optimized.

> **Note:**
> 
> As a good practice, always use the `-coalesce` argument whenever you perform image size manipulations.

### Gifsicle

[Gifsicle ](https://www.lcdf.org/gifsicle/) is a command-line tool specifically designed for creating, editing, and optimizing GIF images and animations. When it comes to image size manipulation, its features are very similar to those of ImageMagick, however, Gifsicle includes the following GIF specific features:

- **Optimization (`--optimize` or `-O`):** This is Gifsicle’s core strength. It performs various lossless and lossy optimizations to reduce file size, including:

  - **Lossless optimization (levels 1, 2, 3):** Reduces redundant data, compresses color tables, and removes unused colors. Higher levels perform more aggressive optimization.
  - **Lossy optimization (—lossy):** Introduces small, imperceptible changes to the image data to achieve greater compression. Values range from 0 (not lossy) to 200 (more loss, smaller file).  
Example of lossless optimization:  
Terminal window  
```bash
gifsicle input.gif -O1 > output_O1.gif
```
Example of lossy optimization:  
Terminal window  
```bash
gifsicle input.gif -O3 --lossy=30 > output_lossy_30.gif
```
- **Color Reduction (—colors):** Specifies the number of colors (less than 256) in the GIF’s palette, which can lead to significant file size reduction. Example:  
Terminal window  
```bash
gifsicle input.gif --colors 128 > output_colors_128.gif
```
- **Dither (—dither):** Applies dithering when reducing colors to smooth out transitions and minimize banding. Example:  
```
gifsicle input.gif --colors 64 --dither > output_colors_64_dithered.gif
```
- **Delay (—delay):** Sets the delay time for frames. A delay value of 20 is equal to 0.2 seconds. Example:  
```
gifsicle input.gif "#0-4" --delay 20 > output_first_5_frames_delay_20.gif
```

#### Reduce frames by half

This method combines Gifsicle syntax with shell command substitution to create a GIF file with half the frames of the original file after skipping every second frame.

```
gifsicle -U input.gif `seq -f "#%g" 0 2 {numberOfFrames}` -O3 -o output.gif
```

> **Note:**
> 
> Gifsicle considers the first frame of the file as `0`. If your GIF file has 96 frames, you must input `95` as the number of frames.

The resulting animation plays at double the speed after removing half of the frames. To correct for playback speed, take the following steps:

1. Find the frame delay of the original file:  
```
gifsicle -I input.gif
```
2. Multiply the delay by `2`.
3. Apply the delay (in hundredths of a second) while skipping frames:  
```
gifsicle -U input.gif -d20 `seq -f "#%g" 0 2 {numberOfFrames}` -O3 -o output.gif
```
This example sets the global frame delay at 0.2 seconds (`-d20`) up from a hypothetical 0.1 seconds in the original file.

## Alternative: use animated WebP format

If you are unsure that your GIF file is not optimized enough to work with Image Resizer, Arc XP recommends using the animated WebP format instead. The animated WebP format offers the following advantages over animated GIF files:

- **More efficient compression.** WebP files are smaller than comparable GIF files thanks to its compression derived from video codecs (on average, 64% smaller when using lossy WebP).
- **Full color depth.** The WebP format supports 24-bit color and an 8-bit alpha channel for higher quality and more vibrant animations. This also provides high-quality retention when downsizing image dimensions.
- **Wide support.** Most modern browsers support the animated WebP format.

The only downside of using the WebP format is that its creation requires more advanced tools and availability of open source tools can be limited.
