Skip to content

Instantly share code, notes, and snippets.

@Mhs-220
Created November 14, 2020 08:55
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 Mhs-220/643a0f38cf48a604d072982e3cbaaf6e to your computer and use it in GitHub Desktop.
Save Mhs-220/643a0f38cf48a604d072982e3cbaaf6e to your computer and use it in GitHub Desktop.
Batch image resize with convert
#!/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