Optimize images size on Mac

When creating a website, developers have to take care of assets size as those can impact negatively your website performances. It will make your website slow for your visitors especially if they connect through a slow mobile carrier.

Fortunately there are easy ways to optimize your image assets with the following on Mac. To do so, you need to navigate to the directory where your image are located and then launch the following commands to optimize them. It will replace your big images by lighter versions without loosing quality.

Install required optimizers

This will install required optimizers with Homebrew. Make sure to have it installed first.

# For JPEG
brew install jpegoptim

# For PNG
brew install optipng

Optimize a single image

# For JPEG
jpegoptim -m80 -o -p --strip-all <image-path>

# For PNG
optipng -o7 <image-path>

Automate this on all found images

# For JPEG
find . -name "*.jpg" -exec jpegoptim -m80 -o -p --strip-all {} \;

# For PNG
find . -name "*.png" -exec optipng -o7 {} \;

As a small explanation, these commands are doing the following:

  • find the files having there names matching the -name regexp
  • execute the command after -exec, the double bracket {} is used to inject the found image path to the command