xrforge/manyfold/root/bin/random_thumbnail.sh

76 lines
2.5 KiB
Bash
Executable file

#!/bin/sh
test -n "$2" || { echo "Usage: $0 <input.jpg> <output.jpg> [blurtimes]"; exit 0; }
# --- Configuration ---
# Define the size of the rectangle to crop (Width x Height)
CROP_SIZE="128x128"
CROP_WIDTH=128
CROP_HEIGHT=128
BLURTIMES=0
test -n "$3" && BLURTIMES=$3
# Input and Output filenames
INPUT_FILE="$1" # <-- **CHANGE THIS** to your actual input file name
OUTPUT_FILE="$2"
# --- Pre-Check: Ensure the input file exists ---
if [ ! -f "$INPUT_FILE" ]; then
echo "🚨 Error: Input file '$INPUT_FILE' not found."
echo "Please update the INPUT_FILE variable in the script."
exit 1
fi
# --- 1. Get the dimensions of the input image ---
# The 'identify' command returns image info; we use awk/cut to extract just the dimensions.
# Example output format: "1920x1080"
IMAGE_GEOMETRY=$(identify -format "%wx%h" "$INPUT_FILE")
IMAGE_WIDTH=$(echo "$IMAGE_GEOMETRY" | cut -dx -f1)
IMAGE_HEIGHT=$(echo "$IMAGE_GEOMETRY" | cut -dx -f2)
echo "Input Image: $INPUT_FILE (${IMAGE_GEOMETRY})"
echo "Crop Area: $CROP_SIZE"
# --- 2. Calculate the maximum possible starting coordinates ---
# To ensure the 16x16 crop doesn't go off the edge:
# Max_X_Start = Image_Width - Crop_Width
# Max_Y_Start = Image_Height - Crop_Height
MAX_X=$((IMAGE_WIDTH - CROP_WIDTH))
MAX_Y=$((IMAGE_HEIGHT - CROP_HEIGHT))
# Check if the image is too small to crop
if [ $MAX_X -lt 0 ] || [ $MAX_Y -lt 0 ]; then
echo "🚨 Error: Image dimensions ($IMAGE_GEOMETRY) are smaller than the crop size ($CROP_SIZE)."
exit 1
fi
# --- 3. Generate Random Coordinates ---
# $RANDOM generates a pseudo-random integer (0 to 32767).
# We use the modulo operator (%) to limit it to the required range (0 to MAX_X or MAX_Y).
# Random X-coordinate (0 to MAX_X)
RANDOM_X=$((RANDOM % (MAX_X + 1)))
# Random Y-coordinate (0 to MAX_Y)
RANDOM_Y=$((RANDOM % (MAX_Y + 1)))
# --- 4. Assemble the ImageMagick Geometry String ---
# The final geometry string is: <Width>x<Height>+<X_Offset>+<Y_Offset>
CROP_GEOMETRY="${CROP_SIZE}+${RANDOM_X}+${RANDOM_Y}"
echo "Random Start Coordinate: X=${RANDOM_X}, Y=${RANDOM_Y}"
echo "ImageMagick Crop String: ${CROP_GEOMETRY}"
# --- 5. Execute the ImageMagick Command ---
# 'convert' is the core command.
# -crop: Specifies the geometry string for cropping.
# -quality 100: (Optional) Ensures best quality for the output JPEG.
test -f $OUTPUT_FILE && rm $OUTPUT_FILE
magick "$INPUT_FILE" \
-crop "$CROP_GEOMETRY" \
-blur 0x$BLURTIMES \
-quality 100 \
"$OUTPUT_FILE"
echo "✅ thumbnail generated"