Skip to content

Instantly share code, notes, and snippets.

@bgrins
Created October 2, 2024 03:10

Revisions

  1. bgrins created this gist Oct 2, 2024.
    57 changes: 57 additions & 0 deletions convert-images.sh
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,57 @@
    #!/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"