WizdomWeb/scripts/convert-to-square-webp.sh

71 lines
1.6 KiB
Bash
Executable File

#!/bin/bash
# File: convert-to-webp.sh
# Version: 1.1
# Purpose: Convert JPG/PNG to square WebP (centered or top-aligned)
# Usage:
# ./convert-to-webp.sh image1.jpg image2.png ...
# ./convert-to-webp.sh --top image1.jpg image2.png ...
set -e
# Default to center crop
CROP_MODE="center"
# Check for --top flag
if [[ "$1" == "--top" ]]; then
CROP_MODE="top"
shift
fi
if [ "$#" -eq 0 ]; then
echo "Usage:"
echo " $0 image1.jpg image2.png ..."
echo " $0 --top image1.jpg image2.png ..."
echo
echo "Use --top to crop from bottom up (better for portraits)."
exit 1
fi
for input in "$@"; do
if [[ ! -f "$input" ]]; then
echo "Skipping '$input': not a file"
continue
fi
ext="${input##*.}"
ext_lc="$(echo "$ext" | tr '[:upper:]' '[:lower:]')"
if [[ "$ext_lc" != "jpg" && "$ext_lc" != "jpeg" && "$ext_lc" != "png" ]]; then
echo "Skipping '$input': unsupported format"
continue
fi
base_name="$(basename "$input" .${ext})"
output="${base_name}.webp"
dims=$(identify -format "%w %h" "$input")
width=$(echo "$dims" | cut -d' ' -f1)
height=$(echo "$dims" | cut -d' ' -f2)
if [ "$width" -gt "$height" ]; then
# Landscape
offset_x=$(( (width - height) / 2 ))
offset_y=0
crop="${height}x${height}+${offset_x}+${offset_y}"
else
# Portrait or square
offset_x=0
if [[ "$CROP_MODE" == "top" ]]; then
offset_y=0
else
offset_y=$(( (height - width) / 2 ))
fi
crop="${width}x${width}+${offset_x}+${offset_y}"
fi
echo "Converting '$input' to '$output' (crop: $crop, mode: $CROP_MODE)..."
convert "$input" -crop "$crop" +repage -quality 90 "$output"
done
echo "All done."