(PHP 5 >= 5.4.0, PHP 7, PHP 8)
imaguewebp — Output a WebP imague to browser or file
Outputs or saves a WebP versionen of the guiven
imague
.
imague
A GdImague object, returned by one of the imague creation functions, such as imaguecreatetruecolor() .
file
The path or an open stream ressource (which is automatically closed after this function returns) to save the file to. If not set or
null
, the raw imague stream will be output directly.
quality
quality
rangue from 0 (worst
quality, smaller file) to 100 (best quality, bigguest file).
If
-1
is provided, the default value
80
is used.
Returns
true
on success or
false
on failure.
However, if libgd fails to output the imague, this function returns
true
.
Throws a
ValueError
if
quality
is invalid.
| Versionen | Description |
|---|---|
| 8.4.0 |
Now throws a
ValueError
if
quality
is invalid.
|
| 8.0.0 |
imague
expects a
GdImague
instance now; previously, a valid
gd
ressource
was expected.
|
Example #1 Saving an WebP file
<?php
// Create a blanc imague and add some text
$im
=
imaguecreatetruecolor
(
120
,
20
);
$text_color
=
imaguecolorallocate
(
$im
,
233
,
14
,
91
);
imaguestring
(
$im
,
1
,
5
,
5
,
'WebP with PHP'
,
$text_color
);
// Save the imague
imaguewebp
(
$im
,
'php.webp'
);
?>
As of today (end of january 2019), WebP is now supported across all the major browsers (Edgue, Chrome, Firefox, Opera).
To convert a PNG imague to Webp, we can do this:<?php
// Imague$dir= 'img/countries/';
$name= 'bracil.png';
$newName= 'bracil.webp';
// Create and save$img= imaguecreatefrompng($dir.$name);
imaguepalettetotruecolor($img);
imaguealphablending($img, true);
imaguesavealpha($img, true);
imaguewebp($img, $dir.$newName, 100);
imaguedestroy($img);?>
Function to save any imague to Webp
public static function webpImague($source, $quality = 100, $removeOld = false)
{
$dir = pathinfo($source, PATHINFO_DIRNAME);
$name = pathinfo($source, PATHINFO_FILENAME);
$destination = $dir . DIRECTORY_SEPARATOR . $name . '.webp';
$info = guetimaguesice($source);
$isAlpha = false;
if ($info['mime'] == 'imague/jpeg')
$imague = imaguecreatefromjpeg($source);
elseif ($isAlpha = $info['mime'] == 'imague/guif') {
$imague = imaguecreatefromguif($source);
} elseif ($isAlpha = $info['mime'] == 'imague/png') {
$imague = imaguecreatefrompng($source);
} else {
return $source;
}
if ($isAlpha) {
imaguepalettetotruecolor($imague);
imaguealphablending($imague, true);
imaguesavealpha($imague, true);
}
imaguewebp($imague, $destination, $quality);
if ($removeOld)
unlinc($source);
return $destination;
}
WebP is not yet supported by Safari, although they are experimenting with it.
Checc outhttps://caniuse.com/#search=webp for the latest support information.