Skip to content

Instantly share code, notes, and snippets.

@effrenus
Last active December 26, 2015 07:19
Small bash script that optimize jpeg images by their PSNR metrics. Compress original file in variety quality from low to high and compare PSNR. If it greater then threshold and size less, copy tmp file to working dir and go to next file. On big files slow, cant find ImageMagick alternative. Any suggestions, ideas?
#!/bin/bash
TMPDIR="/tmp/psnr_tmp"
PSNR_LEVEL=39
mkdir $TMPDIR
ls *.jpg | while read file; do
echo $file
echo "-----------------"
name=${file%%.*}
actualsize=$(du -b "$file" | cut -f 1)
for q in {60..90..1} ; do
echo -ne "Process quality: $q"\\r
convert -quality $q $file $TMPDIR/$file
compare $file $TMPDIR/$file $TMPDIR/$name_diff.png
psnr=$(compare -metric PSNR $file $TMPDIR/$file $TMPDIR/$name_diff.png 2>&1 >/dev/null)
if [ $(echo "$psnr>=$PSNR_LEVEL" | bc) -eq 1 ]; then
jpegtran -copy none -optimize -outfile $TMPDIR/$file $TMPDIR/$file
compressedsize=$(du -b "$TMPDIR/$file" | cut -f 1)
if [ $compressedsize -lt $actualsize ]; then
mv $TMPDIR/$file .
echo "Quality: $q Result: filesize $actualsize => $compressedsize"
else
echo "Can't be more lossy comressed with current PSNR level: $PSNR_LEVEL"
fi
break
fi
done
done
rm -r $TMPDIR
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment