avatar

ShīnChvën ✨

Effective Accelerationism

Powered by Druid

Watermark Your Images from Command-line Interface

Mon May 08 2023

I wrote a bash script that can be run as a command to watermark image or images within the given directory using ImageMagick.

#!/usr/bin/env bash

# Check if source directory or image file and watermark text are provided
if [ $# -eq 0 ]; then
  echo "Usage: $0 <source_dir_or_image_path> [<watermark_text>]"
  exit 1
fi

# Set watermark text to "@ShinChven" if not given
if [ -z "$2" ]; then
  watermark_text="@ShinChven"
else
  watermark_text="$2"
fi

# Create watermark_images directory under the source directory (if a directory path is used)
if [ -d "$1" ]; then
  mkdir -p "$1/watermark_images"
elif [ -f "$1" ]; then
  mkdir -p "$(dirname "$1")/watermark_images"
fi

# Function to add watermark to a single image file
function watermark_image {
  # Add watermark to image and save to watermark_images directory
  watermarked_image="$1/watermark_images/$(basename "$2")"
  convert "$2" -gravity center -strip -pointsize 36 -fill 'rgba(255,255,255,0.3)' -draw "text 0,0 '$3'" "$watermarked_image"
  echo "Watermarked $2 to $watermarked_image"
}

# Check if source path is a file
if [ -f "$1" ]; then
  # Check if file is an image
  if [[ "$1" == *.jpg || "$1" == *.jpeg || "$1" == *.png ]]; then
    watermark_image "$(dirname "$1")" "$1" "$watermark_text"
  else
    echo "Error: $1 is not an image file"
    exit 1
  fi
elif [ -d "$1" ]; then
  # Loop through all images in the source directory
  for image in "$1"/*.jpg "$1"/*.jpeg "$1"/*.png; do
    # Check if image is a file
    if [ -f "$image" ]; then
      watermark_image "$1" "$image" "$watermark_text"
    fi
  done
else
  echo "Error: $1 is not a valid file or directory"
  exit 1
fi

Before using the script, make sure you have ImageMagick installed. You can install it using brew install imagemagick on macOS or sudo apt-get install imagemagick on Ubuntu.

And please replace your default watermark_text in the script with your own default watermark.

ShinChven/watermark-cli