DEV Community

Cover image for Resize images and put a watermark image on it with bash script
Tarik Manoar
Tarik Manoar

Posted on

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.

Top comments (1)

Collapse
 
sasagoji profile image
Gojo

We currently employ 23 R&D Water Purifier Manufacturer specialists, 20 sales professionals, 38 inspectors, and more than 200 competent operators, all of whom contribute their knowledge in our vast 60,000-square-meter facility.