#!/bin/bash CONVERT=$(which convert) IDENTIFY=$(which identify) if [ "$CONVERT" = "" ] ; then echo convert is not found. exit fi if [ "$IDENTIFY" = "" ] ; then echo identify is not found. exit fi BACKUP_DIR="__images_backup" OPTIMIZED_FLAG="fsn:optimized" CONVERTED_COUNTER=0 SKIPPED_COUNTER=0 WRONG_COUNTER=0 function optimize { UPLOADS_PATH="$1" for image in $(find $UPLOADS_PATH -type f -exec file {} \; | awk -F: '{if ($2 ~/image/) print $1}'); do if [[ "$image" == *"$BACKUP_DIR"* ]] ; then continue fi IS_OPTIMIZED=$($IDENTIFY -verbose $image | grep $OPTIMIZED_FLAG) if [ "" != "$IS_OPTIMIZED" ] ; then SKIPPED_COUNTER=$[$SKIPPED_COUNTER + 1] continue fi dirname=$(dirname "$image") filename=$(basename "$image") extension="${filename##*.}" if [ ! -d "${dirname}/${BACKUP_DIR}" ] ; then mkdir "${dirname}/${BACKUP_DIR}" echo "Deny From All" > "${dirname}/${BACKUP_DIR}/.htaccess" fi input_image="${dirname}/${BACKUP_DIR}/${filename}" cmd="" case $(echo "$extension" | tr '[:upper:]' '[:lower:]') in "png" ) cmd="$CONVERT '$input_image' -strip '$image'" ;; "gif" ) cmd="$CONVERT '$input_image' -strip '$image'" ;; "jpg"|"jpeg" ) cmd="$CONVERT '$input_image' -sampling-factor 4:2:0 -strip -quality 60 -interlace JPEG -colorspace sRGB '$image'" ;; * ) echo "Wrong image type: $image" WRONG_COUNTER=$[WRONG_COUNTER + 1] ;; esac if [ "" != "$cmd" ] ; then mv $image $input_image eval $cmd $CONVERT $image -set comment "$OPTIMIZED_FLAG" $image CONVERTED_COUNTER=$[$CONVERTED_COUNTER + 1] fi done } optimize "../../../uploads/" optimize "../images/" echo "Converted $CONVERTED_COUNTER file(s)" echo "Skipped $SKIPPED_COUNTER file(s)" echo "With wrong type $WRONG_COUNTER file(s)" exit 0