Lessons

Using the WebP format in images

The WebP format has absorbed all the best from JPEG and PNG. It can specify the compression ratio of the image from 0 to 100, like JPEG, and it supports transparency, like PNG. Moreover, the compression algorithm is often more efficient than the JPEG format.

The only disadvantage of this format is that it is not supported by operating systems by default. That is, users will not be able to download to their computer and open a WebP file. To do this, they will need to install additional software. But in the browser it always opens.

When converting JPEG and PNG to WebP, it is recommended to specify a compression quality of 90. This will greatly reduce the file size compared to 100 quality, while the image will be almost identical to the maximum quality. It is better to save GIF images without compression.

Code for integration

It is necessary to consider the following:

  1. Support WebP 95.86%, and AVIF 94.7%. Check the Accept request header for the image/avif and image/webp strings. So, browsers report that they support these formats.
  2. Each framework and CMS has standard functions for working with images. As a rule, their functionality can be expanded. Therefore, instead of using your function, it is better to extend the standard functions of the framework and CMS. Methods for extending the standard functionality of each system have their own and are called: hooks, events, function redefinition, callbacks. When using your function, you will need to fix a lot of site files in order to change the call to the image generation function to your own. The easiest way is to modify the standard function 1 time, which is used everywhere.

Demonstration
PHP code
HTML code
<?php
/**
 * Сначала убедитесь, что ваша версия PHP поддерживает AVIF и WebP. Для этого используйте функцию phpinfo() или выполните:
 * php -i | grep AVIF
 * AVIF Support => enabled
 * php -i | grep WebP
 * WebP Support => enabled
 *
 * В случае отсутствия поддержки форматов AVIF и WebP нужно их настроить. Инструкции для вашей операционной системы можно найти в интернете.
 *
 * Для ubuntu обновите вашу версию PHP из репозитория ppa:ondrej/php. Для этого выполните:
 * add-apt-repository ppa:ondrej/php
 * apt update
 * apt upgrade php8.3
 *
 * Вместо 8.3 укажите свою версию PHP.
 */

/**
 * Функция конвертирующая изображения в формате PNG, JPEG, GIF в AVIF, WebP
* - Проверяет, поддерживает ли браузер данный формат
* - GIF изображения конвертирует с качеством 100
* @param string $sourcePath — абсолютный или относительный путь до изображения
* @param int $quality — качество
* @return string — путь SRC
 */
function img2avif($sourcePath, $quality = 90) {
    // Узнаём поддерживаемые браузером форматы
    $accept = $_SERVER['HTTP_ACCEPT'] ?? null;
    // Получаем информацию о файле
    $info = pathinfo($sourcePath);
    // Путь до конвертированного файла
    $path = ($info['dirname'] ? $info['dirname'] . DIRECTORY_SEPARATOR : '') . $info['filename'] . '.';
    // Путь до корня публичной директории
    $root = $_SERVER['DOCUMENT_ROOT'] ?? '';
    // Проверяем поддержку форматов и сгенерированные файлы
    if(strpos($accept, 'image/webp')) {
        $type = 'webp';
        $path = $path . $type;
    } elseif($accept === null || strpos($accept, 'image/avif')) {
        $type = 'avif';
        $path = $path . $type;
    } else {
        return str_replace($root, '', $sourcePath);
    }
    if(!is_file($path)) {
        // Загружаем картинку в переменную PHP
        $image = imagecreatefromstring(file_get_contents($sourcePath));
        // Для GIF нужно качество 100
        if($info['extension'] === 'gif')
            $quality = 100;
        if($type === 'webp')
            imagewebp($image, $path, $quality);
        elseif($type === 'avif')
            imageavif($image, $path, $quality);
    }
    return str_replace($root, '', $path);
}
?><!DOCTYPE html>
<html>
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <h1>Результат работы PHP функции, конвертирующей JPEG в WebP</h1>
        <img src="<?=img2avif('./photo.jpg')?>" />
    </body>
</html>
<!DOCTYPE html>
<html>
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <h1>Результат работы PHP функции, конвертирующей JPEG в WebP</h1>
        <img src="./photo.jpg" />
    </body>
</html>

PRO subscription for working with the service

Promo
To prepare a commercial offer.
190 ₽
50 pages for 10 days
  • 1 page gives 1 tool launch Checking the page.
  • Purchased for a specific site
  • Restrictions on other tools remain the same
PRO subscription
For regular work on a site or a group of sites.
1 580 ₽
3,500 pages per week. The subscription period is 1 month.
Wallet
A separate page balance that complements the PRO subscription balance.
190 ₽
Number of pages
  • An active PRO subscription is required to use the wallet balance
We use cookies. By continuing to use the site, you agree to the processing of personal data in accordance with privacy policy. I agree