As of today (end of january 2019), WebP is now supported across all the major browsers (Edge, Chrome, Firefox, Opera).
(PHP 5 >= 5.4.0, PHP 7, PHP 8)
imagewebp — Mostra uma imagem WebP no navegador ou grava em arquivo
Motra ou grava uma versão WebP da imagem informada em image
.
image
Um objeto GdImage, retornado por uma das funções de criação de imagem, como imagecreatetruecolor().
file
O caminho ou um recurso de fluxo aberto (que será fechado automaticamente após o retorno desta função) para salvar o arquivo. Se não for definido ou for null
, o fluxo da imagem bruta será enviado diretamente.
quality
quality
varia de 0 (pior
qualidade, arquivo menor) a 100 (melhor qualidade, arquivo maior).
Se -1
for informado, o valor padrão de 80
será usado.
Retorna true
em caso de sucesso ou false
em caso de falha.
Entretanto, se a biblioteca libgd falhar ao gerar a imagem, esta função retornará true
.
Lança um ValueError se quality
for inválido.
Versão | Descrição |
---|---|
8.4.0 |
Agora lança um ValueError se quality for inválido.
|
8.0.0 |
O parâmetro image agora espera uma instância de GdImage;
anteriormente, um resource gd válido era esperado.
|
Exemplo #1 Gravando um arquivo WebP
<?php
// Cria uma imagem vazia e adiciona texto
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5, 'WebP with PHP', $text_color);
// Grava a imagem
imagewebp($im, 'php.webp');
?>
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:
<?php
// 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);
return $destination;
}
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.