问题
I'm having trouble using imagewebp to convert an image to webp.
I use 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 webp-image in Chrome it just shows blank, but with the correct size. If I instead load the image and set headers with PHP (see below) it shows up, but with 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 command line it works as expected.
cwebp -q 100 example.jpg -o example.webp
I'm testing this on Ubuntu 14, Apache 2.4.7 and PHP 5.5.9-1ubuntu4.4.
回答1:
I had same problem, my solution is:
$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:
It works:
$jpg=imagecreatefromjpeg('filename.jpg');
$w=imagesx($jpg);
$h=imagesy($jpg);
$webp=imagecreatetruecolor($w,$h);
imagecopy($webp,$jpg,0,0,0,0,$w,$h);
imagewebp($webp, 'filename.webp', 80);
imagedestroy($jpg);
imagedestroy($webp);
来源:https://stackoverflow.com/questions/26314508/convert-jpg-to-webp-using-imagewebp