This script is very useful if you want to create a web photo gallery and so, optimize the browsing speed. The best way in this case is to create from a source folder structure that contains photo files, lower resolution and thumbnail pictures. This script uses the ImageMagick Convert Command-Line Tool.

Requirements for this script :

  • Variables
    • source : folder that contains pictures
    • dest_thumb : folder that will contains thumbnail pictures (200px)
    • dest_resize : folder that will contains resized pictures (1080px)
  • Software
    • Imagemagick

If the source folder contains subfolders you have to create first the subfolder structure for the dest_thumb and dest_resize :
for example, we have the following folders :

source="/test/images/full/"
dest_thumb="/test/images/thumbnail/"
dest_resize="/test/images/resized/"

Execute the following commands :

rsync -av -f"+ */" -f"- *" /test/images/full/ /test/images/thumbnail
rsync -av -f"+ */" -f"- *" /test/images/full/ /test/images/resized

You can then launch the following script to create the resized pictures.

Script :

#!/bin/sh
ProcessInstances=0
ProcessInstances=`ps | grep resize.sh |grep -v grep |wc -l`
echo $ProcessInstances
if [ $ProcessInstances -le 2 ];
then
	echo Process not running! Starting process
	dest_thumb="/test/images/thumbnail/"
	dest_resize="/test/images/resized/"
	source="/test/images/full/"
	find "${source[@]}"$1 -follow -type f | egrep -i ".jpg|.jpeg" | while read line
	do
		dest_thumb_file=`echo $line | sed -e "s|$source|$dest_thumb|g"`
		dest_thumb_dir=`dirname $dest_thumb_file`
		dest_resized_file=`echo $line | sed -e "s|$source|$dest_resize|g"`
		dest_resized_dir=`dirname $dest_resized_file`
		if [ ! -d "$dest_thumb_dir" ]; then
			mkdir "$dest_thumb_dir"
		fi
		if [ ! -d "$dest_resized_dir" ]; then
			mkdir "$dest_resized_dir"
		fi
		if [ ! -f "$dest_thumb_file" ];
		then
			echo "Converting the file $line to thumbnail..."
			convert "$line" -thumbnail x200 -resize '200x<' -resize 50% -gravity center -crop 100x100+0+0 +repage -format jpg -quality 91 -auto-orient "$dest_thumb_file"
		fi
		if [ ! -f "$dest_resized_file" ];
		then
			echo "Converting the file $line to 1080x..."
			convert "$line" -geometry x1080 -auto-orient "$dest_resized_file"
		fi
	done
else
	echo Process already running! Nothing to do.
fi

Reference :
Imagemagick Convert

Automatic pictures resizing with Imagemagick (medium and small size)

Leave a Reply

Your email address will not be published.