Skip to content

Instantly share code, notes, and snippets.

@noelruault
Last active October 5, 2023 08:20
Show Gist options
  • Save noelruault/67e3221c1791a92a40750704c520d0cd to your computer and use it in GitHub Desktop.
Save noelruault/67e3221c1791a92a40750704c520d0cd to your computer and use it in GitHub Desktop.
Script that resizes jpg images to a desired pixel ratio
#!/bin/bash
supported_resolutions=("144" "240" "360" "480" "720" "1024") # Supported resolutions
supported_extensions=("png" "jpg" "jpeg") # Supported image file extensions
selected_output_directory=""
# default_output_directory="img"
selected_resolution=""
while [[ $# -gt 0 ]]; do
case "$1" in
-r|--resolution)
shift
selected_resolution="$1"
shift
;;
-o|--out-dir)
shift
selected_output_directory="$1"
shift
;;
*)
echo "Usage: $0 [-r|--resolution <resolution>] [-o|--out-dir <directory>]"
exit 1
;;
esac
done
if [ -z "$selected_resolution" ]; then # Prompt for resolution if not provided
while [[ ! " ${supported_resolutions[*]} " =~ " $selected_resolution " ]]; do
# read -p "Choose a resolution from the available opts (${supported_resolutions[@]}) " selected_resolution
read -p "Choose a resolution from the available opts (${supported_resolutions[*]}): " selected_resolution
done
fi
echo "You chose resolution: $selected_resolution"
create_dir() {
local dir="$1"
if [ -d "$dir" ]; then
echo "Directory '$dir' already exists."
return 1
else
mkdir -p "$dir"
echo "Created directory '$dir'."
return 0
fi
}
if [ -z "$selected_output_directory" ]; then # Prompt for directory if not provided
while true; do
read -p "Destination directory: " selected_output_directory
if create_dir $selected_output_directory; then
break
fi
done
else
if ! create_dir $selected_output_directory; then
exit 1
fi
fi
# Build the pattern
pattern=""
for ext in "${supported_extensions[@]}"; do
pattern+="*$ext "
done
# Copy files using the pattern
echo "Copying $pattern files to destination folder ($selected_output_directory)"
cp $pattern "$selected_output_directory"
# Function to resize an image using sips
resize_image() {
local file="$1"
sips -Z $selected_resolution "$selected_output_directory/$file" > /dev/null
}
echo "Resizing files to $selected_resolution pixels width..."
# Iterate through the provided arguments (file paths)
for ext in "${supported_extensions[@]}"; do
for file in *.$ext; do
if [ -f "$file" ]; then
# echo "Resizing $file to $selected_resolution pixels width..."
resize_image "$file"
fi
done
done
echo "Done!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment