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.

Top comments (0)