Bitrix: Automatic conversion to webP and display of images in the site template
Rus
Eng
Битрикс: Автоматическая конвертация в webP и вывод изображений в шаблоне сайта

All English-language materials have been translated fully automatically using the Google service

Cross-browser webp usage

Not all safari versions support the webp format at this time. But there is a cross-browser way to use webp

<picture class = "b_426">
<source srcset = "<? = getWebP ($ from)?> 1x, <? = getWebP ($ fromRetina)?> 2x" type = "image / webp">
<source srcset = "<? = $ from?> 1x, <? = $ fromRetina?> 2x" type = "image / jpeg">
<img title = "<? = $ name?>" src = "<? = getWebP ($ small)?>">
</picture> 

How to determine in php that the browser supports webp

But we can use a simpler method. It is somewhat simpler because it allows you to use webp as a background image

/* Checking webp support */
global $WEBP;
if( strpos( $_SERVER['HTTP_ACCEPT'], 'image/webp' ) !== false || strpos($_SERVER['HTTP_USER_AGENT'], ' Chrome/' ) !== false )
	$WEBP = true; // webp supported
else
	$WEBP = false; // webp is not supported

A simple, pain-free way to convert jpg => webp

 function getWebP ($ src) {// Determine whether to add union to the bulk request
    if (! $ src) {
        return false;
    }

    $ source = $ _SERVER ['DOCUMENT_ROOT']. $ src;
    $ destination = $ source. '.webp';

    if (! file_exists ($ destination)) {
        // Maximum, the photo is blurry
        // exec ("cwebp -q 0". $ from. "-o". $ to. "");

        // Normal, good quality with serious compression
        // cwebp -q 80 source.png -o destination.webp
        exec ("convert -colorspace RGB". $ src. "". $ destination. "");
        $ src = $ src. '. webp';
    } else {
        $ src = $ src. '. webp';
    }

    return $ src;
}

$ from = "1.jpg";
$ to = "1.jpg.webp"; 

If the conversion does not take place, then you need to install the utility libwebp

either yourself or through the hoster
 // CentOS 6
sudo apt-get install webp

// CentOS 7
sudo yum install libwebp-tools 

Bash to automatically convert files to webp in the directory

 #! / bin / bash

# converting JPEG images
find $ 1 -type f -and \ (-iname "* .jpg" -o -iname "* .jpeg" \) \
-exec bash -c '
webp_path = $ (sed 's /\. 47,4.►*$/. webp /' <<< "$ 0");
if [! -f "$ webp_path"]; then
  cwebp -quiet -q 90 "$ 0" -o "$ webp_path";
fi; ' {} \;

# converting PNG images
find $ 1 -type f -and -iname "* .png" \
-exec bash -c '
webp_path = $ (sed 's /\. 47,4.►*$/. webp /' <<< "$ 0");
if [! -f "$ webp_path"]; then
  cwebp -quiet -lossless "$ 0" -o "$ webp_path";
fi; ' {} \; 

Bash script taken from here

You can also take libwebp from here

Installing Server Libraries ImageMagickk

Install Development Tools

 yum groupinstall "Development Tools" -y 

Install php-pear, php-devel and gcc packages to compile imagick PHP extension

 yum install php-pear php-devel gcc 

Install ImageMagick

 yum install ImageMagick
yum install ImageMagick-devel
pecl install Imagick 

If all is well, then you will see something like the following:

 Installing '/usr/include/php/ext/imagick/php_imagick_shared.h'
Installing '/usr/lib64/php/modules/imagick.so'
install ok: channel: //pecl.php.net/imagick-3.4.4
configuration option "php_ini" is not set to php.ini location
You should add "extension = imagick.so" to php.ini 

You can check the success of the installation like this:

 convert --version 

Turn on the imagick extension in php.ini

; When the extension library to load is not located in the default extension
; directory, You may specify an absolute path to the library file:
;
; extension = / path / to / extension / mysqli.so
;
; Note: The syntax used in previous PHP versions ('extension = <ext> .so' and
; 'extension =' php_ <ext> .dll ') is supported for legacy reasons and may be
; deprecated in a future PHP major version. So, when it is possible, please
; move to the new ('extension = <ext>) syntax.
extension = imagick.so

We can restart apache , we can not do it (it worked for me and so)

 systemctl reload httpd 

Related article Install ImageMagick in Centos7 < / a>

Installing system libraries

We put the composer through ssh

 php -r "copy ('https://getcomposer.org/installer', 'composer-setup.php');"
php -r "if (hash_file ('sha384', 'composer-setup.php') === 'e0012edf3e80b6978849f5eff0d4b4e4c79ff1609dd1e613307e16318854d24ae64f26 corruptd17af3ef010bf7cfb5cfb setup; setup; php ');} echo PHP_EOL; "
php composer-setup.php
php -r "unlink ('composer-setup.php');" 

Install the WebP Convert library. You can find it here

 composer require rosell-dk / webp-convert 

We use it in Bitrix

In init.php add

require($_SERVER ['DOCUMENT_ROOT'>] .'/local/libs/init/webP.php');

Listing of file webP.php

 require_once ($ _SERVER ['DOCUMENT_ROOT']. '/ vendor / autoload.php');

use WebPConvert \ WebPConvert;
use WebPConvert \ Convert \ Converters \ Stack;
class aWebP
{
    public function __construct () {

    }

    public function getWebP ($ src) {// Determine whether to add union to the bulk request
        if (! $ src) {
            return false;
        }

        $ source = $ _SERVER ['DOCUMENT_ROOT']. $ src;
        $ destination = $ source. '.webp';

        $ options = [
            'fail' => 'original', // If failure, serve the original image (source). Other options include 'throw', '404' and 'report'
            // 'show-report' => true, // Generates a report instead of serving an image
            'serve-image' => [
                'headers' => [
                    'cache-control' => true,
                    'vary-accept' => true,
                    // other headers can be toggled ...
                ],
                'cache-control-header' => 'max-age = 2',
            ],
            'converters' => [
                'cwebp', 'vips', 'imagick', 'gmagick', 'imagemagick', 'graphicsmagick', 'wpc', 'ewww', 'gd'
            ],
        ];

        if (! file_exists ($ destination)) {
            WebPConvert :: convert ($ source, $ destination, $ options);
            $ src = $ src. '. webp';
        } else {
            $ src = $ src. '. webp';
        }

        return $ src;
    }
} 

Use in template

 $ aWebP = new aWebP;
echo $ aWebP-> getWebP ($ imgUrl); 

Conversion options do not work in this case. You will not be able to choose the image quality (I failed, you may succeed).

Using automatic settings will save on average 30-60% on an uncompressed image, 5-15% on a compressed and optimized image via the Bitrix API

Comments

There are no comments yet, you can be the first to leave it

Leave a comment

The site uses a comment pre-moderation system, so your message will be published only after approval by the moderator

You are replying to a user's comment

Send

FEEDBACK

Email me

Are you developing a new service, making improvements to the existing one and want to be better than your competitors? You have come to the right place. I offer you a comprehensive studio-level website development. From me you can order design, layout, programming, development of non-traditional functionality, implementation of communication between CMS, CRM and Data Analitics, as well as everything else related to sites, except for promotion.

Contact, I will always advise on all questions and help you find the most effective solution for your business. I am engaged in the creation of sites in Novosibirsk and in other regions of Russia, I also work with the CIS countries. You will be satisfied with our cooperation

An error occurred while sending, please try again after a while
Message sent successfully

Phones

+7(993) 007-18-96

Email

info@tichiy.ru

Address

Россия, г. Москва

By submitting the form, you automatically confirm that you have read and accept the Privacy Policy site

Contact with me
Send message
By submitting the form, you automatically confirm that you have read and accept Privacy policy of site
Sending successful!
Thank you for contacting :) I will contact you as soon as possible
Sending failed
An error occurred while sending the request. Please wait and try again after a while or call my phone number