Skip to content

Instantly share code, notes, and snippets.

@blairanderson
Last active March 19, 2023 18:34
Show Gist options
  • Save blairanderson/42f5d38aa5e41c17735544d0cad75cfa to your computer and use it in GitHub Desktop.
Save blairanderson/42f5d38aa5e41c17735544d0cad75cfa to your computer and use it in GitHub Desktop.
jpg2png watcher script
#!/bin/bash
# Cleanup product images
# This will convert images from JPG to PNG and replace the white
# background with transparent one.
#
# SEEDED GPT4 a copy of the script from http://tech.natemurray.com/2007/12/convert-white-to-transparent.html
# Set source folder and extension
SRC_EXT=jpg
DST_EXT=png
TRACKER_FILE=".image_tracker"
# This is where all the conversion happens
function removeBackground {
SRC=$1
DST=$2
# Fuzzy percentage level for white color
FUZZ=1
convert "$SRC" \( +clone -fx 'p{0,0}' \) -compose Difference -composite -modulate 100,0 +matte difference.png
convert difference.png -bordercolor white -border 1x1 -matte -fill none -fuzz ${FUZZ}% -draw 'matte 1,1 floodfill' -shave 1x1 removed_black.png
convert removed_black.png -channel matte -separate +matte matte.png
convert matte.png -blur 0x1 matte-negated.png
composite -compose CopyOpacity matte-negated.png "$SRC" "$DST"
rm -f difference.png removed_black.png matte.png matte-negated.png
}
function process_directory {
SRC_FOLDER=$1
if [ ! -f "${SRC_FOLDER}/${TRACKER_FILE}" ]; then
touch "${SRC_FOLDER}/${TRACKER_FILE}"
fi
for FILE in "${SRC_FOLDER}"/*.${SRC_EXT}
do
if [ -f "$FILE" ] && ! grep -q "$FILE" "${SRC_FOLDER}/${TRACKER_FILE}"; then
echo Converting $FILE
NEWFILE="${SRC_FOLDER}/$(basename "$FILE" .${SRC_EXT}).${DST_EXT}"
removeBackground "$FILE" "$NEWFILE"
echo "$FILE" >> "${SRC_FOLDER}/${TRACKER_FILE}"
fi
done
for SUBFOLDER in "${SRC_FOLDER}"/*; do
if [ -d "$SUBFOLDER" ]; then
process_directory "$SUBFOLDER"
fi
done
}
# Check if a folder path is provided
if [ -z "$1" ]; then
echo "Usage: $0 [folder_path]"
exit 1
fi
# Start processing the provided folder and its subfolders
WATCH_FOLDER="$1"
process_directory "$WATCH_FOLDER"
# Watch the folder and its subfolders for new files
fswatch -r -e ".*" -i "\\.${SRC_EXT}$" "$WATCH_FOLDER" | while read -r FILE; do
DIR=$(dirname "$FILE")
process_directory "$DIR"
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment