Watch for changes to a folder using dnotify

This is a neat trick! šŸ™‚

The idea is to watch a folder for changes and then execute a script. A good example is having a folder which people can dump images that need to be resized. To do this, I did the following:

1. Create an In and Out folder. When images are placed in the ‘In’ folder, they’ll be resized and put in the ‘Out’ folder.

2. Create a script that will do the resizing. The following is a messy example:

#!/bin/sh
# Be sure to make this executable: chmod a+x ResizePhotos.sh
if [ "$1" = "" ] ; then
echo "Usage: $0 directory"
exit
fi
# Get list of files in the directory
find "$1" -type f |
#ls $1 -1
while read Name ; do
# Based on the file name, perform the conversion
base=`basename "$Name"`
echo "Found file $base"
case "$Name" in
(*.jpg) # resize the file
echo " Identified as JPEG"
zenity --info --title="Resizing file" --text="The image '$base' will be resized"
newfile="/media/Photos/Resize/Out/smaller_$base"
convert -quality 90 -resize 600 "$Name" "$newfile"
chgrp users "$newfile"
chmod 775 "$newfile"
mv "$Name" "$Name.processed"
;;
(*.JPG) # resize the file
echo " Identified as JPEG"
zenity --info --title="Resizing file" --text="The image '$base' will be resized"
newfile="/media/Photos/Resize/Out/smaller_$base"
convert -quality 90 -resize 600 "$Name" "$newfile"
chgrp users "$newfile"
chmod 775 "$newfile"
mv "$Name" "$Name.processed"
;;
esac
done

3. Add a dnotify line to the /etc/rc.local file to call the script when the ‘In’ folder changes:


dnotify -bC /media/Photos/Resize/In -e /usr/src/ResizePhotos.sh "{}"

4. Done!

You can now add images to the ‘In’ folder and they’ll be resized into the ‘Out’ folder and renamed to .processed in the ‘In’ folder. NOTE: this script doesn’t handle portrait photos very well…that’s a TODO.

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s