Created
October 2, 2024 03:10
-
-
Save bgrins/ba3897a209b929f5f7939d52d71556b5 to your computer and use it in GitHub Desktop.
This file contains 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 | |
DEFAULT_QUALITY=80 | |
# Check if quality values are passed as arguments, if not, use the default | |
AVIF_QUALITY=${1:-$DEFAULT_QUALITY} | |
WEBP_QUALITY=${2:-$AVIF_QUALITY} | |
INPUT_DIR="assets/images" | |
CSV_FILE="conversion_report-$AVIF_QUALITY-$WEBP_QUALITY.csv" | |
echo "Image,File Extension,Original Size (bytes),AVIF Savings (%),WebP Savings (%),AVIF vs WebP Difference (%),AVIF Size (bytes),WebP Size (bytes),AVIF Size Difference (bytes),WebP Size Difference (bytes),avifenc output,cwebp output" > "$CSV_FILE" | |
# OS-specific stat command | |
if [[ "$OSTYPE" == "linux-gnu"* ]]; then | |
STAT_CMD="stat --format=%s" | |
elif [[ "$OSTYPE" == "darwin"* ]]; then | |
STAT_CMD="stat -f %z" | |
else | |
echo "Unsupported OS: $OSTYPE" | |
exit 1 | |
fi | |
sanitize_output() { | |
local raw_output="$1" | |
echo "$raw_output" | tr '\n' ' ' | tr '\r' ' ' | tr '\t' ' ' | sed 's/"/""/g' | |
} | |
for img in "$INPUT_DIR"/*.{png,jpg,jpeg}; do | |
if [[ -f "$img" ]]; then | |
extension="${img##*.}" | |
original_size=$($STAT_CMD "$img") | |
avif_output=$(avifenc -q "$AVIF_QUALITY" "$img" "$img.avif" 2>&1) | |
avif_size=$($STAT_CMD "$img.avif") | |
avif_size_diff=$((original_size - avif_size)) | |
avif_savings_percentage=$(awk "BEGIN {printf \"%.2f\", ($avif_size_diff / $original_size) * 100}") | |
webp_output=$(cwebp "$img" -q "$WEBP_QUALITY" -o "$img.webp" 2>&1) | |
webp_size=$($STAT_CMD "$img.webp") | |
webp_size_diff=$((original_size - webp_size)) | |
webp_savings_percentage=$(awk "BEGIN {printf \"%.2f\", ($webp_size_diff / $original_size) * 100}") | |
avif_webp_difference=$(awk "BEGIN {printf \"%.2f\", (($webp_size - $avif_size) / $original_size) * 100}") | |
sanitized_avif_output=$(sanitize_output "$avif_output") | |
sanitized_webp_output=$(sanitize_output "$webp_output") | |
echo "\"$img\",$extension,$original_size,$avif_savings_percentage%,$webp_savings_percentage%,$avif_webp_difference%,$avif_size,$webp_size,$avif_size_diff,$webp_size_diff,\"$sanitized_avif_output\",\"$sanitized_webp_output\"" >> "$CSV_FILE" | |
echo "Converted $img to AVIF (quality $AVIF_QUALITY) and WebP (quality $WEBP_QUALITY), AVIF savings: $avif_savings_percentage%, WebP savings: $webp_savings_percentage%, AVIF vs WebP difference: $avif_webp_difference%" | |
fi | |
done | |
echo "Conversion report saved to $CSV_FILE" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment