3 回答

TA貢獻1942條經驗 獲得超3個贊
在 7.3.0 上測試 - 有效。
免責聲明:可能僅適用于更高版本或某些 PHP 版本。
僅在 5.6.15(無效,黑色背景)和 7.3.0(有效,透明背景)上測試。
這是代碼:
// get png in question
$pngimg = imagecreatefrompng($file);
// get dimens of image
$w = imagesx($pngimg);
$h = imagesy($pngimg);;
// create a canvas
$im = imagecreatetruecolor ($w, $h);
imageAlphaBlending($im, false);
imageSaveAlpha($im, true);
// By default, the canvas is black, so make it transparent
$trans = imagecolorallocatealpha($im, 0, 0, 0, 127);
imagefilledrectangle($im, 0, 0, $w - 1, $h - 1, $trans);
// copy png to canvas
imagecopy($im, $pngimg, 0, 0, 0, 0, $w, $h);
// lastly, save canvas as a webp
imagewebp($im, str_replace('png', 'webp', $file));
// done
imagedestroy($im);
編輯 1. *** 證明
PHP GD 庫依賴于 libgd 庫。
關聯:
https://github.com/libgd/libgd
保存的相關代碼(文件:gd_webp.c),顯示對 Alpha 通道的尊重(當存在時):
c = im->tpixels[y][x];
a = gdTrueColorGetAlpha(c);
if (a == 127) {
a = 0;
} else {
a = 255 - ((a << 1) + (a >> 6));
}
*(p++) = gdTrueColorGetRed(c);
*(p++) = gdTrueColorGetGreen(c);
*(p++) = gdTrueColorGetBlue(c);
*(p++) = a;
關于 static int _gdImageWebpCtx (gdImagePtr im, gdIOCtx * outfile, int quality)
我提出的PHP代碼依賴于一個事實,即阿爾法在GD庫,因此確實推崇的作品,如果在以后的PHP版本測試不是您正在使用,特別是在我測試了7.3.0,但您的版本后,在早期的版本可能工作。

TA貢獻1835條經驗 獲得超7個贊
您可能必須啟用 Alpha 通道并保存它。也許試試這個:
$ext = $type['ext'];
if ($ext === 'jpg' || $ext === 'jpeg') {
$im = imagecreatefromjpeg($file);
$webp = imagewebp($im, str_replace($ext, 'webp', $file), 70);
} elseif ($ext === 'png') {
$im = imagecreatefrompng($file);
imagepalettetotruecolor($im);
imageAlphaBlending($im, true); // alpha channel
imageSaveAlpha($im, true); // save alpha setting
$webp = imagewebp($file, str_replace('png', 'webp', $file));
}
imagedestroy($im);
PHP的版本是5.6

TA貢獻1804條經驗 獲得超8個贊
如果輸出格式支持完全 alpha 透明度,則無需復制源圖像。相反,在保存時告訴 GD 保留 alpha 通道就足夠了:
$im = imagecreatefrompng($infilename);
imagesavealpha($im, true);
imagewebp($im, $outfilename);
- 3 回答
- 0 關注
- 312 瀏覽
添加回答
舉報