Конвертер в webp php

imagewebp

Выведет или сохранит WebP-версию данного изображения ( image ).

Список параметров

Объект GdImage , возвращаемый одной из функций создания изображений, например, такой как imagecreatetruecolor() .

Путь, или открытый потоковый ресурс (который автоматически закрывается после завершения функции), для сохранения файла. Если не установлен или равен null , изображение будет выведено в поток вывода в бинарном виде.

quality варьируется от 0 (худшее качество, меньший размер файла) до 100 (наилучшее качество, большой файл).

Возвращаемые значения

Возвращает true в случае успешного выполнения или false в случае возникновения ошибки.

Однако, если libgd не может вывести изображения, эта функция вернёт true .

Список изменений

Версия Описание
8.0.0 image теперь ожидает экземпляр GdImage ; ранее ожидался корректный gd ресурс ( resource ).

Примеры

Пример #1 Сохранение WebP-файла

// Создать пустое изображение и добавить текст
$im = imagecreatetruecolor ( 120 , 20 );
$text_color = imagecolorallocate ( $im , 233 , 14 , 91 );

imagestring ( $im , 1 , 5 , 5 , ‘WebP with PHP’ , $text_color );

// Сохранить изображение
imagewebp ( $im , ‘php.webp’ );

// Освободить память
imagedestroy ( $im );
?>

User Contributed Notes 7 notes

As of today (end of january 2019), WebP is now supported across all the major browsers (Edge, Chrome, Firefox, Opera).

To convert a PNG image to Webp, we can do this:

// Image
$dir = ‘img/countries/’ ;
$name = ‘brazil.png’ ;
$newName = ‘brazil.webp’ ;

// Create and save
$img = imagecreatefrompng ( $dir . $name );
imagepalettetotruecolor ( $img );
imagealphablending ( $img , true );
imagesavealpha ( $img , true );
imagewebp ( $img , $dir . $newName , 100 );
imagedestroy ( $img );

Function to save any image to Webp

public static function webpImage($source, $quality = 100, $removeOld = false)
$dir = pathinfo($source, PATHINFO_DIRNAME);
$name = pathinfo($source, PATHINFO_FILENAME);
$destination = $dir . DIRECTORY_SEPARATOR . $name . ‘.webp’;
$info = getimagesize($source);
$isAlpha = false;
if ($info[‘mime’] == ‘image/jpeg’)
$image = imagecreatefromjpeg($source);
elseif ($isAlpha = $info[‘mime’] == ‘image/gif’) $image = imagecreatefromgif($source);
> elseif ($isAlpha = $info[‘mime’] == ‘image/png’) $image = imagecreatefrompng($source);
> else return $source;
>
if ($isAlpha) imagepalettetotruecolor($image);
imagealphablending($image, true);
imagesavealpha($image, true);
>
imagewebp($image, $destination, $quality);

if ($removeOld)
unlink($source);

WebP is not yet supported by Safari, although they are experimenting with it.

Check out https://caniuse.com/#search=webp for the latest support information.

Safari on mac now has limited support (limited to Safari 14+ on Big Sur or later)

Safari on iOS 14.4 and higher has full support

WebP is a great file format, but it’s basically supported only by Chrome. For WebP files with transparency it’s necessary to have PNG fallback for other browsers (otherwise it won’t work in iOS, Firefox, IE, etc.).

Читайте также:  Float64 to float python

Regular truecolor PNG with alpha gives pretty large files, but there’s a special smaller PNG file variant that can be created by pngquant — a command line utility.

If you have pngquant 1.8 on your server (just get package from official pngquant website), then you can create small fallback images (with quality better than from PHP’s libgd):

/**
* Optimizes PNG file with pngquant 1.8 or later (reduces file size of 24-bit/32-bit PNG images).
*
* You need to install pngquant 1.8.x on the server (ancient version 1.0 won’t work).
* There’s package for Debian/Ubuntu and RPM for other distributions on http://pngquant.org
*
* @param $path_to_png_file string — path to any PNG file, e.g. $_FILE[‘file’][‘tmp_name’]
* @param $max_quality int — conversion quality, useful values from 60 to 100 (smaller number = smaller file)
* @return string — content of PNG file after conversion
*/
function compress_png ( $path_to_png_file , $max_quality = 90 )
if (! file_exists ( $path_to_png_file )) throw new Exception ( «File does not exist: $path_to_png_file » );
>

// guarantee that quality won’t be worse than that.
$min_quality = 60 ;

// ‘-‘ makes it use stdout, required to save to $compressed_png_content variable
// ‘ // escapeshellarg() makes this safe to use with any path
$compressed_png_content = shell_exec ( «pngquant —quality= $min_quality — $max_quality — < " . escapeshellarg ( $path_to_png_file ));

if (! $compressed_png_content ) throw new Exception ( «Conversion to compressed PNG failed. Is pngquant 1.8+ installed on the server?» );
>

return $compressed_png_content ;
>
?>

So for example when user is uploading a PNG file:

$read_from_path = $_FILE [ ‘file’ ][ ‘tmp_name’ ];
$save_to_path = «uploads/compressed_file.png» ;

$compressed_png_content = compress_png ( $read_from_path );
file_put_contents ( $save_to_path , $compressed_png_content );

// you don’t need move_uploaded_file().

// and for webp:
imagewebp ( imagecreatefrompng ( $read_from_path ), $save_to_path + «.webp» );
?>

And then you can use URL with .webp version in Chrome and browsers that send Accept: image/webp, and .png for the rest (and all will get small file!)

Источник

imagecreatefromwebp

imagecreatefromwebp() returns an image identifier representing the image obtained from the given filename. Note that animated WebP files cannot be read.

A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.

Parameters

Return Values

Returns an image object on success, false on errors.

Читайте также:  Изменение формы кнопки css

Changelog

Version Description
8.0.0 On success, this function returns a GDImage instance now; previously, a resource was returned.

Examples

Example #1 Convert an WebP image to a jpeg image using imagecreatefromwebp()

// Load the WebP file
$im = imagecreatefromwebp ( ‘./example.webp’ );

// Convert it to a jpeg file with 100% quality
imagejpeg ( $im , ‘./example.jpeg’ , 100 );
imagedestroy ( $im );
?>

User Contributed Notes 1 note

Normal WebP (VP8): supported since PHP 5.4
Transparent WebP or alpha transparency (VP8X, VP8L): supported since PHP 7.0
Animated WebP (VP8X): not supported at all.

Test with imagecreatefromwebp(‘your-image.webp’); and see the errors.

You can detect animated or transparent webp using this code.

/**
* Get WebP file info.
*
* @link https://www.php.net/manual/en/function.pack.php unpack format reference.
* @link https://developers.google.com/speed/webp/docs/riff_container WebP document.
* @param string $file
* @return array|false Return associative array if success, return `false` for otherwise.
*/
function webpinfo ( $file ) if (! is_file ( $file )) return false ;
> else $file = realpath ( $file );
>

$fp = fopen ( $file , ‘rb’ );
if (! $fp ) return false ;
>

$header_format = ‘A4Riff/’ . // get n string
‘I1Filesize/’ . // get integer (file size but not actual size)
‘A4Webp/’ . // get n string
‘A4Vp/’ . // get n string
‘A74Chunk’ ;
$header = unpack ( $header_format , $data );
unset( $data , $header_format );

if (!isset( $header [ ‘Riff’ ]) || strtoupper ( $header [ ‘Riff’ ]) !== ‘RIFF’ ) return false ;
>
if (!isset( $header [ ‘Webp’ ]) || strtoupper ( $header [ ‘Webp’ ]) !== ‘WEBP’ ) return false ;
>
if (!isset( $header [ ‘Vp’ ]) || strpos ( strtoupper ( $header [ ‘Vp’ ]), ‘VP8’ ) === false ) return false ;
>

if (
strpos ( strtoupper ( $header [ ‘Chunk’ ]), ‘ANIM’ ) !== false ||
strpos ( strtoupper ( $header [ ‘Chunk’ ]), ‘ANMF’ ) !== false
) $header [ ‘Animation’ ] = true ;
> else $header [ ‘Animation’ ] = false ;
>

if ( strpos ( strtoupper ( $header [ ‘Chunk’ ]), ‘ALPH’ ) !== false ) $header [ ‘Alpha’ ] = true ;
> else if ( strpos ( strtoupper ( $header [ ‘Vp’ ]), ‘VP8L’ ) !== false ) // if it is VP8L, I assume that this image will be transparency
// as described in https://developers.google.com/speed/webp/docs/riff_container#simple_file_format_lossless
$header [ ‘Alpha’ ] = true ;
> else $header [ ‘Alpha’ ] = false ;
>
>

  • GD and Image Functions
    • gd_​info
    • getimagesize
    • getimagesizefromstring
    • image_​type_​to_​extension
    • image_​type_​to_​mime_​type
    • image2wbmp
    • imageaffine
    • imageaffinematrixconcat
    • imageaffinematrixget
    • imagealphablending
    • imageantialias
    • imagearc
    • imageavif
    • imagebmp
    • imagechar
    • imagecharup
    • imagecolorallocate
    • imagecolorallocatealpha
    • imagecolorat
    • imagecolorclosest
    • imagecolorclosestalpha
    • imagecolorclosesthwb
    • imagecolordeallocate
    • imagecolorexact
    • imagecolorexactalpha
    • imagecolormatch
    • imagecolorresolve
    • imagecolorresolvealpha
    • imagecolorset
    • imagecolorsforindex
    • imagecolorstotal
    • imagecolortransparent
    • imageconvolution
    • imagecopy
    • imagecopymerge
    • imagecopymergegray
    • imagecopyresampled
    • imagecopyresized
    • imagecreate
    • imagecreatefromavif
    • imagecreatefrombmp
    • imagecreatefromgd2
    • imagecreatefromgd2part
    • imagecreatefromgd
    • imagecreatefromgif
    • imagecreatefromjpeg
    • imagecreatefrompng
    • imagecreatefromstring
    • imagecreatefromtga
    • imagecreatefromwbmp
    • imagecreatefromwebp
    • imagecreatefromxbm
    • imagecreatefromxpm
    • imagecreatetruecolor
    • imagecrop
    • imagecropauto
    • imagedashedline
    • imagedestroy
    • imageellipse
    • imagefill
    • imagefilledarc
    • imagefilledellipse
    • imagefilledpolygon
    • imagefilledrectangle
    • imagefilltoborder
    • imagefilter
    • imageflip
    • imagefontheight
    • imagefontwidth
    • imageftbbox
    • imagefttext
    • imagegammacorrect
    • imagegd2
    • imagegd
    • imagegetclip
    • imagegetinterpolation
    • imagegif
    • imagegrabscreen
    • imagegrabwindow
    • imageinterlace
    • imageistruecolor
    • imagejpeg
    • imagelayereffect
    • imageline
    • imageloadfont
    • imageopenpolygon
    • imagepalettecopy
    • imagepalettetotruecolor
    • imagepng
    • imagepolygon
    • imagerectangle
    • imageresolution
    • imagerotate
    • imagesavealpha
    • imagescale
    • imagesetbrush
    • imagesetclip
    • imagesetinterpolation
    • imagesetpixel
    • imagesetstyle
    • imagesetthickness
    • imagesettile
    • imagestring
    • imagestringup
    • imagesx
    • imagesy
    • imagetruecolortopalette
    • imagettfbbox
    • imagettftext
    • imagetypes
    • imagewbmp
    • imagewebp
    • imagexbm
    • iptcembed
    • iptcparse
    • jpeg2wbmp
    • png2wbmp

    Источник

    WebP вместо изображений в браузерах где он поддерживается

    В данной статье приведены примеры как сделать подгрузку WebP вместо jpg и png в тех браузерах где он поддерживается.

    Конвертация в WEBP через SSH

    Самый быстрый способ – конвертировать изображения с помощью утилиты cwebp (если он установлен на сервере) через SSH.

    Нужно выполнить следующую команду, например через PuTTY, которая найдет все файлы изображений и сгенерирует рядом с ними файлы WebP.

    find /public_html/www -iname '*.jpg' -o -iname '*.jpeg' -o -iname '*.png' -exec sh -c 'cwebp -lossless $1 -o "$.webp"' _ <> \;

    /public_html/www – директория, в которой будет осуществляться поиск. Если указать ./ то поиск и конвертация пройдет на всем сервере.

    Cwebp в работе

    Конвертация в WEBP в Windows

    Если сайт очень редко обновляется, то можно выкачивать весь сайт по FTP, конвертировать изображение и закачать обратно. Пакетно перекодировать изображения можно с помощью программы XnConvert.

    Добавление директории с файлами сайта

    Настройки конвертации в WebP

    Процесс конвертации в WebP

    PHP-скрипт

    Еще один вариант конвертации – PHP-скрипт, который вызывается по URL на несуществующий файл *.webp, ищет в той же директории файл с расширением png или jpg и создает из него файл WebP. Главное чтобы на хостинге была установлена библиотека GD версией не ниже 2.2.5, т.к. в более ранних версиях у WebP нет поддержки прозрачности при конвертации из PNG. Посмотреть версию GD можно в phpinfo() :

    Версия PHP GD в phpinfo()

    RewriteEngine On RewriteCond % !-f RewriteCond % /uploads/.*?\.webp$ RewriteRule ^(.*)$ auto-webp.php [L]

    auto-webp.php

     > // Преобразование if (!empty($src)) < $img = false; $info = getimagesize($src); switch ($info[2]) < case 2: $img = imageCreateFromJpeg($src); imageWebp($src, $new, 100); imagedestroy($img); break; case 3: $img = imageCreateFromPng($src); imagepalettetotruecolor($img); imagealphablending($img, true); imagesavealpha($img, true); imageWebp($img, $new, 100); imagedestroy($img); break; >if ($img) < //fix for corrupted WEBPs if (filesize($new) % 2 == 1) < file_put_contents($new, "\0", FILE_APPEND); >// Вывод webp в браузер header('Content-Length: ' . filesize($new)); readfile($new); exit(); > > > header('HTTP/1.0 404 Not Found'); exit();

    Вывод на сайте

    После выбора метода и генерации изображений встает вопрос о выводе их на сайте, специально для этого есть элементы и , которые дают возможность браузеру выбрать более подходящее для него формат. По спецификации изображение WebP правильно вывести в таком виде, с дублированием основного изображения.

        Конвертер в webp php
       Конвертер в webp php

    Если изображения выводятся на страницы сайта из БД в PHP-скриптах, то сделать вывод можно следующим образом:

    Второй вариант – полная замена расширений в тегах если браузер передал в user agent что поддерживает WebP с помощью PHP буферизации и её функции обратного вызова.

    Источник

Оцените статью