Watch a folder to optimize pictures

Purpose

The Image converter application is great. However, we can work faster converting pictures without having to drag and drop them into the application icon.

Instead, we'll setup a local img folder with a watching script. As soon as we add new files into this folder, they will get processed by the web optimization process (resize and jpg compression).

Creating the plist file

The plist file is the one telling macOS: "Watch this folder, and whenever something get changed, execute this command".

We create the following file:

~/Library/LaunchAgents/com.yoricm.watchimg.plist:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.yoricm.watchimg.plist</string>
    <key>StandardErrorPath</key>
  <string>/Users/ym/Documents/__Boulot/__yoricm/__dl/watch_img/err.log</string>
    <key>StandardOutPath</key>
  <string>/Users/ym/Documents/__Boulot/__yoricm/__dl/watch_img/out.log</string>
    <key>EnvironmentVariables</key>
    <dict>
        <key>PATH</key>
        <string>/usr/local/bin:/usr/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin</string>
    </dict>
    <key>WorkingDirectory</key>
    <string>/Users/ym/Documents/__Boulot/__yoricm/__dl/watch_img</string>
    <key>ProgramArguments</key>
    <array>
        <string>/bin/bash</string>
        <string>watch_img.sh</string>
    </array>
    <key>WatchPaths</key>
    <array>
        <string>/Users/ym/Documents/__Boulot/__yoricm/__dl/img</string>
    </array>
    <key>KeepAlive</key>
    <false/>
</dict>
</plist>

We create the img and watch_img folders

cd ~/Documents/__Boulot/__yoricm/__dl
mkdir watch_img
mkdir img

Bash script

We create the following script:

~/Documents/__Boulot/__yoricm/__dl/watch_img/watch_img.sh

#!/bin/bash

for f in ../img/*
do
  [ -f "$f" ] || break
  ext="${f##*.}"
  newf="${f/%.$ext/.jpg}"
  /usr/local/bin/convert -resize 980x980 -quality 60 "$f" "${newf}"
  mv "${newf}" "../site/img/${newf##*/}"
done

Loading the plist file

We load the plist file so it's ready to work:

launchctl load ~/Library/LaunchAgents/com.yoricm.watchimg.plist`