Resize images and put a watermark image on it with bash script

tarikmanoar

Tarik Manoar

Posted on February 8, 2023

Resize images and put a watermark image on it with bash script

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

#!/bin/bash

# Set the desired size
SIZE=800

# Set the watermark image file
WATERMARK=watermark.png

# 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
  # Add the watermark to the image
  composite -dissolve 50% -gravity SouthEast $WATERMARK $FILE $FILE
  # Optimize the image
  mogrify -strip -interlace Plane -gaussian-blur 0.05 -quality 85% $FILE
  echo "Optimized and watermarked: $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 composite command is then used to add a watermark to the image. The watermark image file is specified with the WATERMARK variable. 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 and has a watermark added, a message indicating the optimized and watermarked image is displayed.

💖 💪 🙅 🚩
tarikmanoar
Tarik Manoar

Posted on February 8, 2023

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

Sign up to receive the latest update from our blog.

Related