Skip to content

Instantly share code, notes, and snippets.

@oxagast
Last active January 10, 2024 00:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oxagast/a5558a42eca820ce2e4fe0beb6e8c378 to your computer and use it in GitHub Desktop.
Save oxagast/a5558a42eca820ce2e4fe0beb6e8c378 to your computer and use it in GitHub Desktop.
Batch image file size reducer
#!/bin/bash
# Image size reducing script
#
# oxagast <=> Mark Stealer Whitehall
trap cleanup INT
function cleanup()
{
echo "Cleaning up..."
rm -f /tmp/img_reduce.f.$$.dat /tmp/img_reduce.pics.$$.dat
}
function help()
{
echo "$0 -s ~/Media/Pictures/ -d Small_Pics/ -r 40%"
echo "$0 -s ~/Media/Pictures/ -d Small_Pics/ -r 60% -m 180 -t 8"
exit 1;
}
function progress()
{
tail -f /tmp/img_reduce.f.$$.dat | pv -l -s $totalf -p -N "Converting" 1>/dev/null
}
function threadedconvert()
{
echo "Aggregating files to convert..."
find "$src/" -type f \( -name "*.jpg" -or -name "*.JPG" -or -name "*.png" \) -print >/tmp/img_reduce.pics.$$.dat
totalf=$(cat /tmp/img_reduce.pics.$$.dat | wc -l)
echo "Starting reduce on $totalf pictures using $threads thread(s)..."
(
cat /tmp/img_reduce.pics.$$.dat | while read file; do
((i = i % threads))
((i++ == 0)) && wait
justfile=$(echo "$file" | awk -F "/" '{ print $NF }')
justfile=$(echo "$justfile" | awk -F "." '{ print $1 }')
if [ "$maxsz" == "0" ]; then
convert "$file" -resize "$picsz" "$dst/$justfile.jpg" >/dev/null 2>&1 &
else
convert "$file" -resize "$picsz" -define jpeg:extent="$maxsz"kb "$dst/$justfile.jpg" >/dev/null 2>&1 &
fi
echo "$file" >>/tmp/img_reduce.f.$$.dat
done
) &
}
threadset=0
maxszset=0
srcset=0
dstset=0
picszset=0
while getopts "s:d:r:m:t:h" arg; do
case $arg in
s)
src=$OPTARG
srcset=1
;;
d)
dst=$OPTARG
dstset=1
;;
r)
picsz=$OPTARG
picszset=1
;;
m)
maxsz=$OPTARG
maxszset=1
;;
t)
procs=$OPTARG
threadset=1
;;
h | *)
help
;;
esac
done
shift $((OPTIND - 1))
if [ $threadset -eq 1 ]; then
threads="$procs"
else
threads=8
fi
if [ $maxszset -eq 0 ]; then
maxsz=0
fi
if [ $srcset -ne 1 ] || [ $dstset -ne 1 ] || [ $picszset -ne 1 ]; then
help
else
echo >/tmp/img_reduce.f.$$.dat
echo >/tmp/img_reduce.pics.$$.dat
if test ! -d $dst; then
mkdir $dst
fi
src=$(echo "$src" | sed 's:/*$::')
dst=$(echo "$dst" | sed 's:/*$::')
threadedconvert "$src" "$dst" "$picsz" "$maxsz" "$threads"
progress
cleanup
exit 0
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment