如何解决为什么这种 PHP 图像转换方法会创建完全透明的图像? 问题
我正在使用以下方法将图像批量转换为 .webp
格式(借自 here):
public function convertToWebp($file,$compression_quality = 80) {
// check if file exists
if (!file_exists($file)) {
return false;
}
// If output file already exists return path
$output_file = $file . '.webp';
if (file_exists($output_file)) {
return $output_file;
}
$file_type = strtolower(pathinfo($file,PATHINFO_EXTENSION));
if (function_exists('imagewebp')) {
switch ($file_type) {
case 'jpeg':
case 'jpg':
$image = imagecreatefromjpeg($file);
break;
case 'png':
$image = imagecreatefrompng($file);
imagepalettetotruecolor($image);
imagealphablending($image,true);
imagesavealpha($image,true);
break;
case 'gif':
$image = imagecreatefromgif($file);
break;
default:
return false;
}
// Save the image
$result = imagewebp($image,$output_file,$compression_quality);
if (false === $result) {
return false;
}
// Free up memory
imagedestroy($image);
return $output_file;
} elseif (class_exists('Imagick')) {
$image = new Imagick();
$image->readImage($file);
if ($file_type === 'png') {
$image->setImageFormat('webp');
$image->setImageCompressionQuality($compression_quality);
$image->setOption('webp:lossless','true');
}
$image->writeImage($output_file);
return $output_file;
}
return false;
}
在视图文件中:
foreach ($images as $image) {
<img class="img-responsive" src="<?= convertToWebp($image);?>"/>
}
问题
虽然大多数图像转换成功,但有些图像是完全透明的。
缺少什么?
如果 Imagick 库不支持 .webp
,有什么好的解决方法?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。