Convert jpg to webp with imagewebp
I am having trouble using imagewebp to convert image to webp.
I am using this code:
$filename = dirname(__FILE__) .'/example.jpg';
$im = imagecreatefromjpeg($filename);
$webp =imagewebp($im, str_replace('jpg', 'webp', $filename));
imagedestroy($im);
var_dump($webp);
$ webp returns true, but when I try to view the web image in Chrome it just shows blank but with the correct size. If I instead load an image and set the headers from PHP (see below), it displays, but with the wrong colors (too much yellow).
$im = imagecreatefromwebp('example.webp');
header('Content-Type: image/webp');
imagewebp($im);
imagedestroy($im);
If I convert the same image with the command line, it works as expected.
cwebp -q 100 example.jpg -o example.webp
I am testing this on Ubuntu 14, Apache 2.4.7 and PHP 5.5.9-1ubuntu4.4.
+3
source to share
1 answer
I had the same problem, my solution:
$file='hnbrnocz.jpg';
$image= imagecreatefromjpeg($file);
ob_start();
imagejpeg($image,NULL,100);
$cont= ob_get_contents();
ob_end_clean();
imagedestroy($image);
$content = imagecreatefromstring($cont);
imagewebp($content,'images/hnbrnocz.webp');
imagedestroy($content);
+2
source to share