Skip to content

Instantly share code, notes, and snippets.

@imkh
Last active July 29, 2021 19:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save imkh/1e349de95879d22445550f3ac222fc0f to your computer and use it in GitHub Desktop.
Save imkh/1e349de95879d22445550f3ac222fc0f to your computer and use it in GitHub Desktop.
Split all landscape images in a directory in half

split_landscape.sh

Find all landscape images in a directory (sub directories included) and split them in half from right to left. For the opposite direction, remove the magick -reverse option on line 32.

Requires imagemagick (brew install imagemagick on macOS).

$ cd [directory]
$ ./split_landscape.sh

or

$ ./split_landscape.sh [directory]
#!/usr/bin/env sh
if [[ -z "$1" ]]; then
DIRECTORY="."
else
DIRECTORY="$1"
fi
echo "🔄 Looking for image files in \"$DIRECTORY\""
# Loop recursively through image files in a directory
### Alternative method to find image files (requires GNU grep: brew install grep)
### find "$DIRECTORY" -name '*' -exec file {} \; | ggrep -o -P '^.+: \w+ image'
find "$DIRECTORY" -type f -print0 | xargs -0 file --mime-type | grep -F 'image/' | cut -d ':' -f 1 | while read FILE_PATH; do
r=$(magick identify -format '%[fx:(w>h)]' "$FILE_PATH") # Check whether the file is portrait or landscape
if [[ r -eq 1 ]] # 0 -> landscape and 1 -> portrait
then
# FILE_PATH = ``../directory/image.jpg`
FILE_NAME="${FILE_PATH%.*}" # FILE_NAME = `../directory/image`
FILE_EXTENSION="${FILE_PATH##*.}" # FILE_EXTENSION = `jpg`
OUTPUT=""$FILE_NAME"_%d.$FILE_EXTENSION" # OUTOUT = `../directory/image_%d.jpg`
magick identify -format "%[input] %[magick] %[width]x%[height] %[bit-depth]-bit %[colorspace]\n" "$FILE_PATH"
## Debugging
# echo "FILE_PATH = $FILE_PATH"
# echo "FILE_NAME = $FILE_NAME"
# echo "FILE_EXTENSION = $FILE_EXTENSION"
# echo "OUTPUT = $OUTPUT"
# echo "----------"
magick "$FILE_PATH" -crop 2x1@ -reverse +repage "$OUTPUT" # Split image file in half with output file names reversed for right-to-left
rm "$FILE_PATH" # Delete landscape file
fi
done
echo "✅ Done!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment