Skip to content

Instantly share code, notes, and snippets.

@joncardasis
Created April 5, 2019 20:28
Show Gist options
  • Save joncardasis/d5085e2f93cb2ce3461aa37246aaaa91 to your computer and use it in GitHub Desktop.
Save joncardasis/d5085e2f93cb2ce3461aa37246aaaa91 to your computer and use it in GitHub Desktop.
Compresses and optimizes png image sizes for a given file or directory via pngquant.
#!/bin/bash
# Compresses and optimizes png image sizes for a given file or directory.
# @author: Jonathan Cardasis
CHECK_MARK="\033[0;32m\xE2\x9C\x94\033[0m"
PNGQUANT_BINARY_URL="https://pngquant.org/pngquant.tar.bz2"
optimize() {
ORIGINAL_PATH="$1"
NEW_PATH="$ORIGINAL_PATH.new"
pngquant --skip-if-larger "$ORIGINAL_PATH" --output "$NEW_PATH"
if [ "$?" -eq 0 ]; then
rm "$ORIGINAL_PATH"
mv "$NEW_PATH" "$ORIGINAL_PATH"
fi
}
kb_count_of() {
echo $(bc <<< "scale=2; $(wc -c "$1" | awk '{print $1}')/1000")
}
if [ "$#" -lt 1 ]; then
echo "Provide a file or directory to optimize."
exit 1
fi
# Check for pngquant installation
if [ "$1" == "--install" ]; then
TEMP_DIR=`mktemp -d -t 'pngquant'`
cd "$TEMP_DIR"
curl -sS "$PNGQUANT_BINARY_URL" | tar xf - && \
cp pngquant /usr/local/bin
exit_code=$?
if [ $exit_code -eq 0 ]; then
echo "pngquant installed successfully."
else
echo "pngquant failed to install."
fi
rm -r "$TEMP_DIR"
exit $exit_code
elif ! command -v pngquant > /dev/null; then
echo "pngquant is not installed. Run with the '--install' flag to install pngquant.";
exit 1
fi
# Optimize
echo -e "\n\033[4mOptimizing Images\033[0m"
total_original_kb=0
optimized_total_kb=0
if [ -f "$1" ]; then
total_original_kb=$(kb_count_of "$1")
optimize "$1"
optimized_total_kb=$(kb_count_of "$1")
elif [ -d "$1" ]; then
FILES=()
while IFS= read -r -d $'\0'; do
FILES+=("$REPLY")
done < <(find "${1%/}" -name "*.png" -print0)
total_files="${#FILES[@]}"
echo "count: $total_files"
for filepath in "${FILES[@]}"; do
filename=$(basename "$filepath")
echo -n "Optimizing $filename ..."
original_size_kb=$(kb_count_of "$filepath")
total_original_kb=$(bc <<< "$total_original_kb + $original_size_kb")
optimize "$filepath" > /dev/null 2>&1
optimized_size_kb=$(kb_count_of "$filepath")
optimized_total_kb=$(bc <<< "$optimized_total_kb + $optimized_size_kb")
percent_diff=$(bc <<< "scale=2; ($original_size_kb-$optimized_size_kb)/$original_size_kb * 100")
echo -e "\r${CHECK_MARK} Optimized $filename | \033[0;32m${percent_diff}% smaller\033[0m"
done
echo ""
fi
savings_size_kb=$(bc <<< "$total_original_kb-$optimized_total_kb")
echo -e "Finished optimizing. \033[0;32m${savings_size_kb}Kb saved.\033[0m"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment