Skip to content

Instantly share code, notes, and snippets.

@clemlesne
Created November 7, 2023 15:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save clemlesne/c58c49b7756730235138a8d80a7371dd to your computer and use it in GitHub Desktop.
Save clemlesne/c58c49b7756730235138a8d80a7371dd to your computer and use it in GitHub Desktop.
Make transaprent and crop an image
#!/bin/bash
# Display help with -h parameter
function display_help {
echo "Usage: $0 -i <image-path>"
echo
echo " -h Display this help message."
echo " -i <image-path> Specify the image path for processing."
echo
exit 1
}
# No arguments, print help
if [ $# -eq 0 ]; then
display_help
fi
# Parse arguments
while getopts "hi:" opt; do
case $opt in
h)
display_help
;;
i)
image_path="$OPTARG"
;;
\?)
echo "Invalid option: -$OPTARG" >&2
display_help
;;
esac
done
# Check if image file is provided and exists
if [ -z "$image_path" ]; then
echo "Error: No image path provided."
exit 1
fi
if [ ! -f "$image_path" ]; then
echo "Error: File does not exist."
exit 1
fi
# Test ImageMagick before execution
if ! convert --version &> /dev/null; then
echo "Error: ImageMagick is not installed or not in PATH."
exit 1
fi
# Create a temporary directory
temp_dir=$(mktemp -d)
trap 'rm -rf -- "$temp_dir"' EXIT
# Remove background from image
bg_removed_image="$temp_dir/bg_removed.png"
convert "$image_path" -background none -flatten "$bg_removed_image"
# Convert white pixels to transparent
transparent_image="$temp_dir/transparent.png"
convert "$bg_removed_image" -transparent white "$transparent_image"
# Crop image size to content
cropped_image="$temp_dir/cropped.png"
convert "$transparent_image" -trim "$cropped_image"
# Prepare the new image path with -new suffix
filename=$(basename -- "$image_path")
extension="${filename##*.}"
filename="${filename%.*}"
new_image_path="$(dirname -- "$image_path")/${filename}-new.$extension"
# Move the final image to the same folder as the source image
mv "$cropped_image" "$new_image_path"
echo "Processing complete. Output image located at $new_image_path"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment