Skip to content

Instantly share code, notes, and snippets.

@chetan
Created February 22, 2019 20:35
Show Gist options
  • Save chetan/b4165e9c09bdda3e2e7a9e6d9b3c86c0 to your computer and use it in GitHub Desktop.
Save chetan/b4165e9c09bdda3e2e7a9e6d9b3c86c0 to your computer and use it in GitHub Desktop.

Revisions

  1. chetan created this gist Feb 22, 2019.
    86 changes: 86 additions & 0 deletions convert.sh
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,86 @@
    #!/bin/bash

    # convert.sh
    # util for generating resized images at multiple common display resolutions


    SIZES="720 750 1080 1100 1440 1680 2880"
    EXTS="jpg JPG jpeg JPEG"

    print_res() {
    for f in "$@"; do
    echo "$f: $(file "$f" | grep -Eo '[0-9]+x[0-9]+' | tail -n 1)";
    done
    }

    split_name() {
    local f=$1
    local e
    filename=""
    ext=""
    for e in $EXTS; do
    echo $f | egrep \."$e"\$ >/dev/null
    if [[ $? -eq 0 ]]; then
    filename=$(basename $f .$e)
    ext="$e"
    return
    fi
    done
    }

    resize() {
    if [ $# -eq 0 ]; then
    return
    fi

    local f=$1

    if [ ! -f "$f" ]; then
    echo "warning: $f not found"
    return
    fi

    echo "* resizing $f ..."

    split_name $f
    if [[ -z "$filename" ]]; then
    echo "error: unknown file ext for $f"
    return
    fi

    # convert images
    for size in $SIZES; do
    echo " - ${size}px"
    convert $f -resize "${size}x" -blur 0x2 "${filename}-${size}w-o.${ext}"
    /usr/local/opt/mozjpeg/bin/cjpeg -outfile "${filename}-${size}w.${ext}" "${filename}-${size}w-o.${ext}"
    rm -f "${filename}-${size}w-o.${ext}"
    done

    echo " done"

    # print srcset for html
    local src
    read -r -d '' src <<-EOF
    srcset="$(for size in $SIZES; do
    echo " ${filename}-${size}w.${ext} ${size}w,";
    done;)"
    EOF
    echo "$src" | sed -E -e 's/" +/"/' | sed -E -e 's/,"$/"/'
    echo

    # print image-set for css
    read -r -d '' src <<-EOF
    image-set($(for size in $SIZES; do
    echo " url(\"${filename}-${size}w.${ext}\") 1x,";
    done;))
    EOF
    echo "$src" | sed -E -e 's/\( +/(/' | sed -E -e 's/,)$/)/'
    }

    if [ $# -eq 0 ]; then
    echo "usage: $0 file.jpg [...]"
    fi

    for f in "$@"; do
    resize "$1"
    done