Skip to content

Instantly share code, notes, and snippets.

@alimd
Created February 9, 2025 13:07
Show Gist options
  • Save alimd/11d389cdc2cf2205077a91b77f354903 to your computer and use it in GitHub Desktop.
Save alimd/11d389cdc2cf2205077a91b77f354903 to your computer and use it in GitHub Desktop.
c2webp - Image to WebP Converter

c2webp - Image to WebP Converter

This script provides a simple command-line function, c2webp, to convert images (JPEG, PNG, TIFF) to the WebP format. It leverages the cwebp command-line tool from Google.

Features

  • Converts single image files or entire directories of images.
  • Supports JPEG, PNG, and TIFF input formats.
  • Allows specifying the output WebP quality.
  • Supports passing additional options directly to the cwebp command.
  • Safe handling of filenames with spaces and special characters.
  • Handles existing .webp input, will replace the old file.
  • Robust error handling and input validation.

Requirements

  • Bash shell
  • cwebp command-line tool. Install it using your system's package manager:
    • Debian/Ubuntu: sudo apt install webp
    • macOS (Homebrew): brew install webp
    • Other systems: Consult the WebP documentation for installation instructions.

Installation

  1. Copy the code from the c2webp.sh file.
  2. Save it to a file (e.g., c2webp.sh).
  3. Make the script executable: chmod +x c2webp.sh
  4. Optional (Recommended): Add the function to your shell's configuration file (e.g., ~/.bashrc, ~/.zshrc):
    • Source the script: source /path/to/c2webp.sh (replace /path/to with the actual path). This makes the c2webp function available in your current and future shell sessions. You could also copy the contents of c2webp.sh (excluding the shebang) directly into your .bashrc.

Usage

c2webp <input> [quality] [options]
  • <input>: Path to a single image file (JPEG, PNG, TIFF) or a directory containing images.
  • [quality]: (Optional) Compression quality (0-100). Default is 80. Higher values mean better quality but larger file sizes.
  • [options]: (Optional) Additional options to pass directly to the cwebp command. See cwebp -longhelp for all available options. Some useful options include:
    • -mt: Use multi-threading for faster encoding (if supported by your cwebp build).
    • -af: Auto-filter (adjusts filtering strength automatically).
    • -lossless: Encode the image without any loss.

Examples

  • Convert a single image with default quality:

    c2webp image.jpg
  • Convert a single image with a specific quality:

    c2webp image.png 95
  • Convert a single image with multi-threading and auto-filter:

    c2webp image.tiff 80 -mt -af
  • Convert all images in a directory:

    c2webp my_images/
  • Convert all images in a directory with a specific quality and lossless encoding:

    c2webp my_images/ 75 -lossless

Error Handling

The script checks for several potential errors:

  • cwebp command not found.
  • Invalid input file or directory.
  • Unsupported file types.
  • Errors during the cwebp conversion process.

Error messages are printed to standard error (stderr). The script returns a non-zero exit code on failure.

Contributing

Feel free to fork this gist and submit pull requests with improvements or bug fixes.

#!/bin/bash
# c2webp - Converts images (JPEG, PNG, TIFF) to WebP format.
c2webp() {
local input="$1"
local quality="${2:-80}" # Use positional parameter for quality
local options="${*:3}" # Capture all remaining arguments as options
local outputFile
# --- Input Validation ---
if [ -z "$input" ]; then
echo "Usage: c2webp <input_file> [quality] [options]" >&2 # Error to stderr
echo " <input_file>: Path to a single image file or a directory." >&2
echo " [quality]: Optional. Compression quality (0-100, default: 80)." >&2
echo " [options]: Optional. Additional cwebp options (e.g., -mt, -af)." >&2
echo "Example: c2webp image.jpg 90 -mt" >&2
echo "Example: c2webp images_directory/ 75 -lossless" >&2
return 1
fi
if ! command -v cwebp &>/dev/null; then
echo "Error: cwebp command not found. Please install the WebP tools." >&2
echo " (e.g., 'apt install webp' on Debian/Ubuntu, 'brew install webp' on macOS, press 'Alt+F4' in Windows)." >&2
return 1
fi
# --- Single File Conversion ---
if [ -f "$input" ]; then
# Avoid double .webp.webp extensions. Also handles existing .webp files.
outputFile="${input}.webp"
echo "Processing: $input"
cwebp -q "$quality" $options "$input" -o "$outputFile"
if [ $? -eq 0 ]; then # Check the exit code of cwebp
echo "Converted: $input -> $outputFile"
else
echo "Error: cwebp failed for $input" >&2
return 1 # Return error if cwebp fails
fi
# --- Directory Conversion ---
elif [ -d "$input" ]; then
# Find supported image files (JPEG, PNG, TIFF, Gif) within the directory.
find "$input" -type f \( -iname "*.jpeg" -o -iname "*.jpg" -o -iname "*.png" -o -iname "*.tiff" -o -iname "*.tif" -o -iname "*.gif" \) -print0 |
while IFS= read -r -d $'\0' file; do
outputFile="${file}.webp"
echo -e "\n\nProcessing: $file"
cwebp -q "$quality" $options "$file" -o "$outputFile"
if [ $? -eq 0 ]; then
echo "Converted: $file -> $outputFile"
else
echo "Error: cwebp failed for $file" >&2
# Don't return here; continue processing other files in the directory.
fi
done
else
echo "Error: Invalid input. '$input' is not a file or directory." >&2
return 1
fi
}
Check if the script is being sourced or executed directly
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
c2webp "$@"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment