revisit crop image script

feat(images): improve JPG crop script reliability and safety

- Add detailed script header, description, and usage instructions
- Process only JPG/JPEG files
- Handle filenames containing spaces safely
- Verify ImageMagick dependencies before execution
- Use identify -format for reliable dimension detection
- Match images with width exactly 3546px
- Skip previously processed *_c.jpg and *_u.jpg files
- Add error handling for invalid or corrupt images
- Enable strict Bash mode (set -euo pipefail)
- Improve logging and processing feedback

move file

crop images
This commit is contained in:
Lucas Vivohost committed 2026-09-14 12:43:38 +02:00
1 parent f84d8d137b
commit c1ebc80235
2 files changed
+81 -12

No files matched your search

+81
View File
@@ -0,0 +1,81 @@
#!/bin/bash
###############################################################################
# Script Name: crop_images.sh
#
# Description:
# Safely processes JPEG images in the current directory. If an image has a
# width of 3546 pixels, the script:
# 1. Creates a cropped copy (2448x3264 from the top-left corner).
# 2. Saves the cropped image as *_c.jpg.
# 3. Renames the original image as *_u.jpg.
#
# Features:
# - Processes only .jpg files.
# - Handles filenames containing spaces.
# - Verifies that ImageMagick is installed.
# - Skips files that have already been processed.
# - Uses ImageMagick's format output instead of parsing command output.
#
# Requirements:
# - Bash
# - ImageMagick (identify, convert)
#
# Usage:
# chmod +x crop_images.sh
# ./crop_images.sh
#
###############################################################################
set -euo pipefail
# Verify required commands exist
for cmd in identify convert; do
command -v "$cmd" >/dev/null 2>&1 || {
echo "Error: '$cmd' command not found. Install ImageMagick."
exit 1
}
done
# Process JPEG files only
for img in *.jpg *.JPG; do
# Skip if no matching files exist
[[ -f "$img" ]] || continue
# Skip files already processed
[[ "$img" =~ _c\.jpg$|_u\.jpg$ ]] && continue
# Get image dimensions (e.g. 3546x4728)
size=$(identify -format "%wx%h" "$img" 2>/dev/null) || {
echo "Skipping invalid image: $img"
continue
}
# Process only images whose width is exactly 3546 pixels
if [[ "$size" == 3546x* ]]; then
echo "Processing: $img ($size)"
cropped="${img%.jpg}_c.jpg"
original="${img%.jpg}_u.jpg"
# Handle uppercase extension
if [[ "$img" == *.JPG ]]; then
cropped="${img%.JPG}_c.jpg"
original="${img%.JPG}_u.jpg"
fi
# Create cropped image
convert "$img" -crop 2448x3264+0+0 "$cropped"
# Rename original image
mv "$img" "$original"
echo " Created: $cropped"
echo " Renamed: $original"
fi
done
echo "Done."
-12
View File
@@ -1,12 +0,0 @@
#!/bin/bash
for img in *; do
size=$(identify ${img} | cut -f3 -d' ')
if [[ "$(echo ${size} | grep 3546)" != "" ]]; then
echo $size
convert $img -crop 2448x3264+0+0 $(echo $img | sed 's/\.jpg/_c\.jpg/g')
mv $img $(echo $img | sed 's/\.jpg/_u\.jpg/g')
fi
done