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.
- 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.
- 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.
- Debian/Ubuntu:
- Copy the code from the
c2webp.sh
file. - Save it to a file (e.g.,
c2webp.sh
). - Make the script executable:
chmod +x c2webp.sh
- 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 thec2webp
function available in your current and future shell sessions. You could also copy the contents ofc2webp.sh
(excluding the shebang) directly into your.bashrc
.
- Source the script:
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 thecwebp
command. Seecwebp -longhelp
for all available options. Some useful options include:-mt
: Use multi-threading for faster encoding (if supported by yourcwebp
build).-af
: Auto-filter (adjusts filtering strength automatically).-lossless
: Encode the image without any loss.
-
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
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.
Feel free to fork this gist and submit pull requests with improvements or bug fixes.