#!/bin/bash
#this script was written to be called with find, something like:
# find . -type f \( -name *.jpg -o -name *.png -o -name *.JPG -o -name *.PNG \) -exec ~/batchImageOptim.sh "{}" \;
if [[ $# == 1 ]]; then
input_file="$1"
else
echo "no arguments, no party"
exit 255
fi
if [ ! -f "$input_file" ]; then
echo "$input_file not found!"
exit 255
fi
if [[ "$input_file" == *"cache"* ]]; then
echo 'archivos en cache not cool dud'
exit 255
fi
SUFFIX='_oldnotoptimyet'
if [[ $input_file == *"$SUFFIX"* ]]; then
echo "archivo contiene $SUFFIX!!!"
echo "$input_file"
correct_name=${input_file//$SUFFIX/}
echo "$correct_name"
echo "$input_file el nombre correcto es $correct_name"
mv "$input_file" "$correct_name"
input_file="$correct_name"
exit 255
fi
FILE_EXTENSION='ext'
if [[ $input_file == *".jpg"* ]]; then
FILE_EXTENSION='jpg'
elif [[ $input_file == *".JPG"* ]]; then
FILE_EXTENSION='jpg'
elif [[ $input_file == *".png"* ]]; then
FILE_EXTENSION='png'
elif [[ $input_file == *".PNG"* ]]; then
FILE_EXTENSION='png'
else
echo 'tipo de imagen no soportado... salimos!'
exit 255
fi
# cambio nombre de archivo para saber que es el bloqueado
temp_file=$(echo $input_file | sed -e "s/\.$FILE_EXTENSION/$SUFFIX\.$FILE_EXTENSION/g")
mv "$input_file" "$temp_file"
if [ ! -f "$temp_file" ]; then
echo "error al mover!"
echo "$input_file"
exit 255
fi
# jpg se optimizan de manera distinta a png:
if [ $FILE_EXTENSION = 'jpg' ]; then
# http://stackoverflow.com/a/7262050
convert -strip -interlace Plane -sampling-factor 4:2:0 -define jpeg:dct-method=float -quality 85% "$temp_file" "$input_file"
elif [ $FILE_EXTENSION = 'png' ]; then
convert "$temp_file" -quality 85 -depth 8 "$input_file"
fi
if [ ! -f "$input_file" ]; then
echo "error al optimizar"
mv "$temp_file" "$input_file"
exit 255
else
rm "$temp_file"
exit 255
fi