Skip to content

Instantly share code, notes, and snippets.

@gardner
Created August 6, 2024 05:03
Show Gist options
  • Save gardner/49819173a6e31d447cc240c720b1883d to your computer and use it in GitHub Desktop.
Save gardner/49819173a6e31d447cc240c720b1883d to your computer and use it in GitHub Desktop.
A macOS folder action that converts files to webp format
#!/usr/bin/env bash -x
export PATH="${PATH}:/opt/homebrew/bin"
for f in "$@"; do
ABSOLUTE_F=$(readlink -f "$f")
# Check if the file is an image
MIME_TYPE=$(file --mime-type -b "$ABSOLUTE_F")
EXT="${ABSOLUTE_F##*.}"
BASENAME="${ABSOLUTE_F##*/}"
# Define the WebP file path, relative to the source file's directory
WEBP_DIR=$(dirname "$ABSOLUTE_F")
WEBP_PATH="$WEBP_DIR/${BASENAME%.*}.webp"
if [[ "$MIME_TYPE" == "image/heic" ]]; then
convert "$ABSOLUTE_F" "$WEBP_PATH"
fi
if [[ "$MIME_TYPE" == "image/tiff" || "$MIME_TYPE" == "image/png" || "$MIME_TYPE" == "image/jpeg" ]]; then
if [ ! -f "$WEBP_PATH" ]; then
echo "Converting $f to WebP format..."
cwebp "$f" -o "$WEBP_PATH"
fi
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment