Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save dkapitan/115da99b8cd4d1885362ed9b0513d84f to your computer and use it in GitHub Desktop.

Select an option

Save dkapitan/115da99b8cd4d1885362ed9b0513d84f to your computer and use it in GitHub Desktop.
Remove background CLI with imagemagick
#!/bin/bash
# Remove solid background color from images, replacing with transparency.
# Usage: ./remove-bg.sh image.jpg [fuzz%]
# fuzz% = color tolerance (default 15%), increase for off-white/gradient backgrounds
# Output: same filename as .png in the same directory.
set -euo pipefail
if [ $# -lt 1 ]; then
echo "Usage: $0 <image> [fuzz%]"
echo " fuzz% - color tolerance, default 15 (e.g. 20 for more aggressive removal)"
exit 1
fi
INPUT="$1"
FUZZ="${2:-1}"
OUTPUT="${INPUT%.*}-nobg.png"
magick "$INPUT" -fuzz "${FUZZ}%" -transparent white -trim +repage "$OUTPUT"
echo "✓ $OUTPUT"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment