DEV Community

Hossein Sadeghi
Hossein Sadeghi

Posted on

PHP WebP Thumbnailer

PHP thumbnailer with WebP support

WebpThumbnailer is a thumbnail helper which allows you to generate and cache image thumbnails in your PHP application on the fly.


php composer.phar require "maximal/php-webp-thumbnailer" "*"
Enter fullscreen mode Exit fullscreen mode

Checking the environment

You will need WebP coder (cwebp command) installed in your system.

For instance in Ubuntu/Debian it is included in webp package:

sudo apt install webp

Check the command:
cwebp -version

You should get an output with version number (like 0.6.1).

If you have installed cwebp to a different command or path, configure the static property

Enter fullscreen mode Exit fullscreen mode

before using the helper (see the example below).

More info about WebP:

Generating thumbnails

Use this thumbnailer in your PHP application:

`use maximal\thumbnail\WebpThumbnailer;

echo WebpThumbnailer::picture('/path/to/img/image.png', $width, $height);`

More options (outbound instead of default inset; alt and class attribute added):

use maximal\thumbnail\WebpThumbnailer;

echo WebpThumbnailer::picture(
    ['alt' => 'Alt attribute', 'class' => 'img-responsive']
Enter fullscreen mode Exit fullscreen mode

Custom cwebp command:

use maximal\thumbnail\WebpThumbnailer;

WebpThumbnailer::$cwebpCommand = '/usr/local/bin/cwebp';
echo WebpThumbnailer::picture('/path/to/img/image.jpg', $width, $height);
Enter fullscreen mode Exit fullscreen mode

The helper’s picture() method uses modern HTML tag as follows:

<picture data-cache="hit|new">
<source srcset="/assets/thumbnails/...image.png.webp" type="image/webp" />
<img src="/assets/thumbnails/...image.png" other-attributes="" />

Here you have image/webp source for browsers which support WebP images and traditional (PNG, JPEG, TIFF, GIF) image fallback.

Useful for photo articles:


Websites: and

Top comments (0)