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 — Imprimir una imagen WebP al navegador o fichero
Imprime o guarda una versión WebP de la imagen dada por image
.
image
Un recurso image, es devuelto por una de las funciones de creación de imágenes, como imagecreatetruecolor().
to
La ruta o un recurso de flujo de apertura (el cual se cierra automáticamente después de que devuelva esta función) donde guardar el fichero. Si no se establece, o su valor es null
, se mostrará directamente en la salida el flujo de imagen sin tratar.
quality
quality
va desde 0 (peor
calidad, fichero más pequeño) a 100 (mejor calidad, fichero más grande).
Versión | Descripción |
---|---|
5.4.0 |
Se añadió soporte para pasar un resource de flujo a
to .
|
Ejemplo #1 Guardar un fichero WebP
<?php
// Crear una imagen en blanco y añadir algo de texto
$im = imagecreatetruecolor(120, 20);
$color_texto = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5, 'WebP con PHP', $color_texto);
// Guardar la imagen
imagewebp($im, 'php.webp');
// Liberar memoria
imagedestroy($im);
?>
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.