Imagick (PHP)
| Language | PHP (C extension) |
|---|---|
| License | PHP License 3.01 (ImageMagick: ImageMagick License, libwebp: BSD-3-Clause) |
| Repository | github.com/Imagick/imagick |
| Documentation | Imagick in the PHP manual, ImageMagick WebP options |
| Depends on | ImageMagick 6 or 7 built with libwebp |
| Read / write | yes / yes, lossy, lossless, alpha, animation, metadata |
Imagick exposes ImageMagick to PHP. ImageMagick uses libwebp, so Imagick reads and writes lossy, lossless and animated WebP and keeps or strips Exif, XMP and ICC profiles. Every cwebp option is available as a webp:* define.
Installation#
Shell
# Debian / Ubuntu
sudo apt install php-imagick
# PECL
pecl install imagick
Check WebP support: php -r 'print_r(Imagick::queryFormats("WEBP"));' must print WEBP.
Basic usage: convert to WebP#
PHP
<?php
$im = new Imagick('photo.jpg');
printf("%d x %d\n", $im->getImageWidth(), $im->getImageHeight());
$im->thumbnailImage(1200, 0); // 0 keeps the aspect ratio
$im->setImageFormat('webp');
$im->setImageCompressionQuality(80); // 0-100
$im->writeImage('photo.webp');
$im->clear();
new Imagick('in.webp') reads WebP the same way.
How to write a lossless WebP with libwebp options#
PHP
<?php
$im = new Imagick('logo.png');
$im->setImageFormat('webp');
$im->setOption('webp:lossless', 'true');
$im->setOption('webp:method', '6'); // 0 = fast .. 6 = smallest
$im->setOption('webp:exact', 'true'); // keep RGB under transparent pixels
$im->writeImage('logo.webp');
Other defines: webp:alpha-quality, webp:use-sharp-yuv, webp:near-lossless, webp:image-hint, webp:target-size.
How to convert an animated GIF to animated WebP#
PHP
<?php
$gif = new Imagick('anim.gif');
$frames = $gif->coalesceImages(); // full frames instead of GIF deltas
foreach ($frames as $frame) {
$frame->setImageFormat('webp');
$frame->setImageCompressionQuality(75);
}
$frames->writeImages('anim.webp', true); // true = one file with all frames
printf("%d frames\n", $frames->getNumberImages());
How to get WebP dimensions without decoding#
PHP
<?php
$im = new Imagick();
$im->pingImage('in.webp'); // reads the header only
printf("%d x %d\n", $im->getImageWidth(), $im->getImageHeight());
How to strip metadata#
PHP
<?php
$im = new Imagick('photo.webp');
$im->stripImage(); // removes Exif, XMP, ICC and comments
$im->writeImage('photo-clean.webp');
Tips#
- Set resource limits for untrusted uploads:
Imagick::setResourceLimit(Imagick::RESOURCETYPE_MEMORY, 256 * 1024 * 1024);. - Older ImageMagick builds without libwebp fail with “no decode delegate for this image format”.