DEV Community

Cover image for How to resize and optimize images with bash script
Tarik Manoar
Tarik Manoar

Posted on

How to resize and optimize images with bash script

Here's a bash script that uses the mogrify command from ImageMagick to optimize and resize all .jpg and .png images in the current directory and display a message indicating which images were optimized:

#!/bin/bash

# Set the desired size
SIZE=800

# Find all .jpg and .png images in the current directory
for FILE in *.jpg *.png
do
  # Check if the file is larger than the desired size
  if [ $(identify -format "%[fx:w]" $FILE) -gt $SIZE ]; then
    # Resize the image
    mogrify -resize $SIZE $FILE
  fi
  # Optimize the image
  mogrify -strip -interlace Plane -gaussian-blur 0.05 -quality 85% $FILE
  echo "Optimized: $FILE"
done

Enter fullscreen mode Exit fullscreen mode

This script uses the identify command from ImageMagick to check the width of each image. If the width is larger than the desired size, it uses the mogrify command to resize the image. The mogrify command is also used to optimize the image by removing unnecessary metadata, applying a small amount of blur, and reducing the quality to 85%. After each image is optimized, a message indicating the optimized image is displayed.

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more