Automated image optimization

hashcode01

Hash

Posted on March 2, 2022

Automated image optimization

Manual tools like photoshop or online websites provide some level of compression. But to fully optimize images for web performance, you need to run them a dedicated tool to this purpose.

There are many tools, that we're going to check 3 of most used of them.

imagemin

It's a good choice, you can use the CLI to optimize all images in a specified folder. or add automated using grunt or webpack or whatever you are using.

import imagemin from 'imagemin';
import imageminJpegtran from 'imagemin-jpegtran';
import imageminPngquant from 'imagemin-pngquant';

const files = await imagemin(['images/*.{jpg,png}'], {
    destination: 'build/images',
    plugins: [
        imageminJpegtran(),
        imageminPngquant({
            quality: [0.6, 0.8]
        })
    ]
});

console.log(files);
//=> [{data: <Buffer 89 50 4e …>, destinationPath: 'build/images/foo.jpg'}

Enter fullscreen mode Exit fullscreen mode

if you run the above code and then check the destination path, you will see the different file sizes and compression rates.

Squoosh

It makes images smaller using best-in-class codecs, right in the browser. besides it provides a CLI that can be used stright from the command line withouth installing using npx:

$ npx @squoosh/cli <options...>
Enter fullscreen mode Exit fullscreen mode

Of course, you can also install the Squoosh CLI:

$ npm i -g @squoosh/cli
$ squoosh-cli <options...>
Enter fullscreen mode Exit fullscreen mode

it's slower than imagemin but it provides better compression.

sharp

It's a high speed module to convert large images in common formats to different dimensions.

As well as image resizing, operations such as rotation, extraction, compositing and gamma correction are available.

it's also easy to use as you can see in below example:

npm install sharp
Enter fullscreen mode Exit fullscreen mode

and how to use it :

sharp('input.jpg')
  .rotate()
  .resize(200)
  .jpeg({ mozjpeg: true })
  .toBuffer()
  .then( data => { ... })
  .catch( err => { ... });
```



with sharp we can produce different dimensions and then we can use `imagemin` to compress them. that would be a good approach then you can create [responsive images](https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images) easily with using `srcset` attribute to use those images in your web development. 
example:



```html
<img srcset="elva-fairy-480w.jpg 480w,
             elva-fairy-800w.jpg 800w"
     sizes="(max-width: 600px) 480px,
            800px"
     src="elva-fairy-800w.jpg"
     alt="Elva dressed as a fairy">
```




Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
hashcode01
Hash

Posted on March 2, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related