# Image Optimization 101

![All the shit we should do](https://1620588615-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LEx__frh5rhJHikGydq%2F-LFTKILdqNgMCMW1eGiH%2F-LFTctLvPVjwgwvtXAED%2Fimage-optimisation.jpg?alt=media\&token=d57748dd-dcce-4a2a-a999-b13e0948958b)

## How can I tell if my images need to be optimized?

Use LightHouse audits in ChromeDev Tools

![](https://1620588615-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LEx__frh5rhJHikGydq%2F-LFTKILdqNgMCMW1eGiH%2F-LFTquUJfxmPf8AzgTYj%2Fhbo.jpg?alt=media\&token=bbfeb957-62ff-4810-b030-d331514f6460)

## Eliminating and replacing images

* &#x20;Eliminate unnecessary image resources
* &#x20;Leverage CSS3 effects where possible
* &#x20;Use web fonts instead of encoding text in images

Some alternative technologies:

* &#x20;**CSS effects** (gradients, shadows, etc.) and CSS animations can be used to produce resolution-independent assets that always look sharp at every resolution and zoom level, often at a fraction of the bytes required by an image file.
* &#x20;**Web fonts** enable use of beautiful typefaces while preserving the ability to select, search, and resize text - a significant improvement in usability.

## Delivering scaled image assets

* &#x20;Delivering scaled assets is one of the simplest and most effective optimizations
* &#x20;Pay close attention to large assets as they result in high overhead
* &#x20;Reduce the number of unnecessary pixels by scaling your images to their display size

![High overhead](https://1620588615-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LEx__frh5rhJHikGydq%2F-LFTKILdqNgMCMW1eGiH%2F-LFToBUa8pkAN7RmI2ah%2Fresized-image.png?alt=media\&token=4543a4a9-8b2f-4ba4-9691-fcc46d9c7c73)

\


## Choose between Vector and Raster images

* &#x20;Vector images are ideal for images that consist of geometric shapes
* &#x20;Raster images should be used for complex scenes with lots of irregular shapes and details

\


![Comparison zoomed-in image of 2 format](https://1620588615-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LEx__frh5rhJHikGydq%2F-LFTKILdqNgMCMW1eGiH%2F-LFTKsHtISd3SC8GKiFW%2F2018-06-21%2000_56_15-Window.png?alt=media\&token=93baaf4a-c595-4982-8547-a8b059b63934)

* &#x20;[Vector graphics](https://en.wikipedia.org/wiki/Vector_graphics) use lines, points, and polygons to represent an image.
* &#x20;[Raster graphics](https://en.wikipedia.org/wiki/Raster_graphics) represent an image by encoding the individual values of each pixel within a rectangular grid.

### Optimizing vector images <a href="#optimizing_vector_images" id="optimizing_vector_images"></a>

* &#x20;SVG is an XML-based image format
* &#x20;SVG files should be minified to reduce their size
* &#x20;SVG files should be compressed with GZIP

Sample SVG file

```

<?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 17.1.0, SVG Export Plug-In . SVG Version: 6.00 Build 0)  -->
<svg version="1.2" baseProfile="tiny" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
   x="0px" y="0px" viewBox="0 0 612 792" xml:space="preserve">
<g id="XMLID_1_">
  <g>
    <circle fill="red" stroke="black" stroke-width="2" stroke-miterlimit="10" cx="50" cy="50" r="40"/>
  </g>
</g>
</svg>
```

### Optimizing raster images <a href="#optimizing_raster_images" id="optimizing_raster_images"></a>

* &#x20;A raster image is a grid of pixels
* &#x20;Each pixel encodes color and transparency information
* &#x20;Image compressors use a variety of techniques to reduce the number of required bits per pixel to reduce file size of the image

![](https://1620588615-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LEx__frh5rhJHikGydq%2F-LFTKILdqNgMCMW1eGiH%2F-LFThPz1k_6WHhBldHiz%2Fartifacts.png?alt=media\&token=10b99371-4481-4230-971e-64dbdd30a419)

{% hint style="info" %}
**Note:** Left to right (PNG): 32-bit (16M colors), 7-bit (128 colors), 5-bit (32 colors). Complex scenes with gradual color transitions (gradients, sky, etc.) require larger color palettes to avoid visual artifacts such as the pixelated sky in the 5-bit asset. On the other hand, if the image only uses a few colors, then a large palette is simply wasting precious bits!
{% endhint %}

## Important factors when optimizing images

### Lossless vs lossy image compression

* &#x20;Due to how our eyes work, images are great candidates for lossy compression
* &#x20;Image optimization is a function of lossy and lossless compression
* &#x20;Differences in image formats are due to the difference in how and which lossy and lossless algorithms are used to optimize the image
* &#x20;There is no single best format or "quality setting" for all images: each combination of particular compressor and image contents produce a unique output

![Save for web in Photoshop](https://1620588615-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LEx__frh5rhJHikGydq%2F-LFTKILdqNgMCMW1eGiH%2F-LFTiKp6WuiNSUFyIoDv%2Fsave-for-web.png?alt=media\&token=28744fb7-b1ac-485c-a011-1cc43879831b)

### Selecting the right image format <a href="#selecting_the_right_image_format" id="selecting_the_right_image_format"></a>

* &#x20;Start by selecting the right universal format: GIF, PNG, JPEG
* &#x20;Experiment and select the best settings for each format: quality, palette size, etc.
* &#x20;Consider adding WebP and JPEG XR assets for modern clients



| **Format**                                                        |  **Transparency** |  **Animation** | **Browser**             |
| ----------------------------------------------------------------- | ----------------- | -------------- | ----------------------- |
|  [GIF](http://en.wikipedia.org/wiki/Graphics_Interchange_Format)  |  Yes              | Yes            |  All                    |
|  [PNG](http://en.wikipedia.org/wiki/Portable_Network_Graphics)    |  Yes              |  No            |  All                    |
|  [JPEG](http://en.wikipedia.org/wiki/JPEG)                        |  No               |  No            |  All                    |
|  [JPEG XR](http://en.wikipedia.org/wiki/JPEG_XR)                  |  Yes              | Yes            |  IE                     |
|  [WebP](http://en.wikipedia.org/wiki/WebP)                        |  Yes              | Yes            |  Chrome, Opera, Android |

\


![Selection chart](https://1620588615-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LEx__frh5rhJHikGydq%2F-LFTKILdqNgMCMW1eGiH%2F-LFTjRDdyBsWjRdN1tES%2Fformat-tree.png?alt=media\&token=e861860f-08d0-4a72-853c-86f571c6a3dd)

Explanation

1\. **Do you need animation? If so, GIF is the only universal choice.**

* &#x20;GIF limits the color palette to at most 256 colors, which makes it a poor choice for most images. Further, PNG-8 delivers better compression for images with a small palette.
* Should **use mp4 or webm** file in shape of GIF

2\. **Do you need to preserve fine detail with highest resolution? Use PNG.**

* &#x20;PNG does not apply any lossy compression algorithms beyond the choice of the size of the color palette. As a result, it will produce the highest quality image, but at a cost of significantly higher filesize than other formats. Use judiciously.
* &#x20;If the image asset contains imagery composed of geometric shapes, consider converting it to a vector (SVG) format!
* &#x20;If the image asset contains text, stop and reconsider. Text in images is not selectable, searchable, or "zoomable". If you need to convey a custom look (for branding or other reasons), use a web font instead.

3\. **Are you optimizing a photo, screenshot, or a similar image asset? Use JPEG.**

* &#x20;JPEG uses a combination of lossy and lossless optimization to reduce filesize of the image asset. Try several JPEG quality levels to find the best quality vs. filesize tradeoff for your asset.
* **Don't use JPEG when saving image contains text. Use PNG instead. JPEG artifact is horrible for text image**

### Key settings when optimizing images

* Select progressive mode (JPEG) or interlaced mode (PNG) when saving/optimizing image
* Strip EXIF data
* Choose chroma subsampling at 4:2:0 or 4:2:2
* JPEG is good for most case, EXCEPT image contains text

![](https://1620588615-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LEx__frh5rhJHikGydq%2F-LFTKILdqNgMCMW1eGiH%2F-LFTpcfq-PMnQftWsVik%2Fvqvqf.gif?alt=media\&token=ae76dbc2-51b9-495a-af2b-faa4352b88fb)

![Choose chroma subsampling at 4:2:0 or 4:2:2](https://1620588615-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LEx__frh5rhJHikGydq%2F-LFTKILdqNgMCMW1eGiH%2F-LFTq4nP6gf9nj6FXxmT%2Fluma-signal.jpg?alt=media\&token=39443ebe-e5dd-499b-8c35-4d3ebb08b158)

## Replace Animated GIFs with Video

### Converting gif to mp4 or webm

Sample command when use **ffmpeg** for converting:

```

ffmpeg -i input.gif output.mp4
ffmpeg -i input.gif -b:v 0 -crf 25 output.mp4
ffmpeg -i input.gif -c vp9 -b:v 0 -crf 41 output.webm
```

### Replacing animated GIF `<img>` elements with `<video>`

&#x20;Animated GIFs have three key traits:

1. &#x20;They play automatically.
2. &#x20;They loop continuously (usually, but it is possible to prevent looping).
3. &#x20;They're silent.

We can produce these behaviors with video:

```markup
<video autoplay loop muted playsinline></video>
```

&#x20;There's more to this than simply emulating GIF behavior, though. Some of these attributes are required for autoplay to even work. For example, [the `muted` attribute _must_ be present](https://developers.google.com/web/updates/2016/07/autoplay) for videos to autoplay, even if they don't contain an audio track. [On iOS, the `playsinline` attribute is required for autoplay to work](https://webkit.org/blog/6784/new-video-policies-for-ios/) as well.
