使用imagewebp将jpg转换为webp

问题描述 投票:4回答:2

我在使用imagewebp将图像转换为webp时遇到麻烦。

我使用此代码:

$filename = dirname(__FILE__) .'/example.jpg';

$im = imagecreatefromjpeg($filename);

$webp =imagewebp($im, str_replace('jpg', 'webp', $filename));
imagedestroy($im);

var_dump($webp);

$ webp返回true,但是当我尝试在Chrome中查看webp图像时,它仅显示空白,但大小正确。如果我改为加载图像并使用PHP设置标头(请参见下文),则会显示出来,但颜色错误(黄色太多)。

$im = imagecreatefromwebp('example.webp');
header('Content-Type: image/webp');
imagewebp($im);
imagedestroy($im);

如果我使用命令行转换相同的图像,它将按预期工作。

cwebp -q 100 example.jpg -o example.webp

我正在Ubuntu 14,Apache 2.4.7和PHP 5.5.9-1ubuntu4.4上进行测试。

php webp
2个回答
5
投票

我有同样的问题,我的解决方法是:

$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);

0
投票

效果很好,谢谢。是否可以更进一步并一次性转换目录中的所有图像?

© www.soinside.com 2019 - 2024. All rights reserved.