GD (PHP)
| Language | PHP (C extension) |
|---|---|
| License | PHP License / BSD-style (libgd), libwebp: BSD-3-Clause |
| Repository | github.com/php/php-src (ext/gd) |
| Documentation | imagewebp, imagecreatefromwebp |
| Depends on | libgd (bundled) built with libwebp |
| Read / write | yes / yes, lossy, lossless (PHP 8.1+), alpha; no animation |
GD ships with PHP and is enabled on most hosts. When it’s compiled with libwebp, imagecreatefromwebp reads WebP and imagewebp writes it. It handles still images with transparency; animated WebP files can’t be read.
GD has a small API and no metadata support: Exif and ICC profiles are dropped. For more control use Imagick.
Installation#
GD is part of PHP. On Linux install the package and check that WebP is enabled:
Shell
# Debian / Ubuntu
sudo apt install php-gd
php -r 'var_dump(gd_info()["WebP Support"] ?? false);'
When compiling PHP yourself, configure with --enable-gd --with-webp. With Docker’s official image: docker-php-ext-configure gd --with-webp --with-jpeg && docker-php-ext-install gd.
Basic usage: convert JPEG to WebP#
PHP
<?php
$im = imagecreatefromjpeg('photo.jpg');
if ($im === false) {
exit("cannot read photo.jpg\n");
}
printf("%d x %d\n", imagesx($im), imagesy($im));
if (!imagewebp($im, 'photo.webp', 80)) { // quality 0-100, default 80
exit("cannot write photo.webp\n");
}
Reading WebP: $im = imagecreatefromwebp('in.webp'); then imagepng($im, 'out.png');.
How to write a lossless WebP#
PHP 8.1 added the IMG_WEBP_LOSSLESS quality value:
PHP
<?php
$im = imagecreatefrompng('logo.png');
imagewebp($im, 'logo.webp', IMG_WEBP_LOSSLESS);
How to keep transparency when converting PNG to WebP#
PHP
<?php
$im = imagecreatefrompng('icon.png');
imagepalettetotruecolor($im); // palette PNGs must become truecolor first
imagealphablending($im, true);
imagesavealpha($im, true);
imagewebp($im, 'icon.webp', 90);
How to get WebP dimensions without decoding#
getimagesize reads only the header:
PHP
<?php
[$width, $height, $type] = getimagesize('in.webp');
if ($type === IMAGETYPE_WEBP) {
echo "$width x $height\n";
}
How to resize a WebP and output it to the browser#
PHP
<?php
$src = imagecreatefromwebp('in.webp');
$thumb = imagescale($src, 400); // 400 px wide, height keeps the aspect ratio
header('Content-Type: image/webp');
imagewebp($thumb, null, 75); // null = write to output
Tips#
imagecreatefromwebpreturnsfalse(with a warning) for animated WebP.- Check
imagetypes() & IMG_WEBPat run time before relying on WebP.