Skip to content

Instantly share code, notes, and snippets.

@chetan chetan/convert.sh

Created Feb 22, 2019
Embed
What would you like to do?
#!/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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.