Created
November 14, 2020 08:55
-
-
Save Mhs-220/643a0f38cf48a604d072982e3cbaaf6e to your computer and use it in GitHub Desktop.
Batch image resize with convert
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# The script takes 3 args. | |
# -s for size (default: 1024) | |
# -i for input folder (default: current dir) | |
# -o for output folder (default: resized) | |
# | |
# For example: | |
# ./resize-image.sh -i pexels -o output_folder -s 1800 | |
# Default Values | |
export INPUT_PATH="." | |
export SIZE="1024" | |
export OUTPUT="resized" | |
# Get Option | |
while getopts ":i:s:o:" opt; do | |
case $opt in | |
i) INPUT_PATH="$OPTARG" | |
;; | |
s) SIZE="$OPTARG" | |
;; | |
o) OUTPUT="$OPTARG" | |
;; | |
\?) echo "Invalid option -$OPTARG" >&2 | |
;; | |
esac | |
done | |
# Create output folder if doesn't exist | |
if [[ ! -d $OUTPUT ]]; then mkdir $OUTPUT; fi | |
# Resize function | |
function convert_files() { | |
# Get file Absolute path | |
file_path=$(readlink -f $1); | |
# Create file name base on path | |
# For example: | |
# ./folder/subfolder/file.extension -> folder-subfolder-file.extension | |
file_name=$1; | |
if [[ $file_name = "./"* ]]; then | |
file_name=${file_name/.\//}; | |
fi | |
file_name=${file_name//\//-}; | |
echo "$file_path Goes to $OUTPUT/$file_name"; | |
convert $file_path -resize "${SIZE}x${SIZE}^>" "$OUTPUT/$file_name"; | |
} | |
export -f convert_files | |
printf "\nInput: %s\nSize: %s\nOutput: %s\n\n" $INPUT_PATH $SIZE $OUTPUT | |
# This is the real magic! | |
find $INPUT_PATH -type f -exec bash -c 'convert_files "$@"' bash {} \; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment