【发布时间】:2021-05-19 19:22:32
【问题描述】:
我有一个实用程序类,它可以加载图像文件,并在其他操作中将它们转换为其他格式。它使用 PHP GD。
一切正常,除了具有透明度的 PNG 文件在转换为 WebP 时出错。结果图像在应为透明度的位置具有黑色背景。
这是我的代码:
class OImage {
private ?GdImage $image = null;
private ?int $image_type = null;
public function load(string $filename): void {
$image_info = getimagesize($filename);
$this->image_type = $image_info[2];
switch ($this->image_type) {
case IMAGETYPE_JPEG: { $this->image = imagecreatefromjpeg($filename); }
break;
case IMAGETYPE_GIF: { $this->image = imagecreatefromgif($filename); }
break;
case IMAGETYPE_PNG: { $this->image = imagecreatefrompng($filename); }
break;
case IMAGETYPE_WEBP: { $this->image = imagecreatefromwebp($filename); }
break;
}
}
public function save(string $filename, int $image_type=IMAGETYPE_JPEG, int $compression=75, int $permissions=null): void {
switch ($image_type) {
case IMAGETYPE_JPEG: { imagejpeg($this->image, $filename, $compression); }
break;
case IMAGETYPE_GIF: { imagegif($this->image, $filename); }
break;
case IMAGETYPE_PNG: { imagepng($this->image, $filename); }
break;
case IMAGETYPE_WEBP: {
imagepalettetotruecolor($this->image);
imagealphablending($this->image, true);
imagesavealpha($this->image, true);
imagewebp($this->image, $filename);
}
break;
}
if (!is_null($permissions)) {
chmod($filename, $permissions);
}
}
...
}
该类有许多其他功能可以调整大小或缩放,但与我的问题无关。我尝试将imagealphablending 和imagesavealpha 设置为true 或false,结果完全相同。
我也在考虑改用 Imagick,但他们还没有 PHP 8 扩展。
我在 Debian 9 和 GD 2.2.4 上使用 PHP 8
有什么帮助吗?
谢谢!
【问题讨论】:
-
以下单行将带有 alpha 的 PNG 转换为带有 alpha 的 WEBP,没有任何问题:
imagewebp(imagecreatefrompng('https://maxcdn.icons8.com/office/PNG/512/Science/alpha-512.png'), 'out.webp');基于此,我的猜测是您的一些调整大小或缩放操作正在删除 alpha在你打电话给save之前的频道。