Skip to content

Instantly share code, notes, and snippets.

@mamchenkov
Created October 24, 2014 08:49
Show Gist options
  • Save mamchenkov/20006d5e0b79c4119dcc to your computer and use it in GitHub Desktop.
Save mamchenkov/20006d5e0b79c4119dcc to your computer and use it in GitHub Desktop.
Convert JPG product images to PNG, replacing white background with transparent one.
#!/bin/bash
# Cleanup product images
#
# This will convert images from JPG to PNG and replace the white
# background with transparent one.
#
# This is almost verbatim copy of the script from:
# http://tech.natemurray.com/2007/12/convert-white-to-transparent.html
SRC_FOLDER=orig
SRC_EXT=jpg
DST_FOLDER=result
DST_EXT=png
# This is where all the conversion happens
function removeBackground {
SRC=$1
DST=$2
# Fuzzy percentage level for white colort
FUZZ=1
# start real
convert "$SRC" \( +clone -fx 'p{0,0}' \) -compose Difference -composite -modulate 100,0 +matte difference.png
# remove the black, replace with transparency
convert difference.png -bordercolor white -border 1x1 -matte -fill none -fuzz ${FUZZ}% -draw 'matte 1,1 floodfill' -shave 1x1 removed_black.png
# create the matte
convert removed_black.png -channel matte -separate +matte matte.png
# negate the colors
#convert matte.png -negate -blur 0x1 matte-negated.png
convert matte.png -blur 0x1 matte-negated.png
# you are going for: white interior, black exterior
composite -compose CopyOpacity matte-negated.png "$SRC" "$DST"
# cleanup
rm -f difference.png removed_black.png matte.png matte-negated.png
}
for FILE in ${SRC_FOLDER}/*.${SRC_EXT}
do
echo Converting $FILE
NEWFILE="${DST_FOLDER}"/$(basename "$FILE" .${SRC_EXT}).${DST_EXT}
removeBackground "$FILE" "$NEWFILE"
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment