如何将png文件转换为webp文件

我需要将图像(png)转换为(webp)文件。


上传png文件后,已经生成了webp图像,但是webp文件并没有复制png文件的透明度,而是创建了一个黑色背景。


这是我的 php 代码:


$type = wp_check_filetype($file, null);

$ext = $type['ext'];

if ($ext === 'png') {

    $im = imagecreatefrompng($file);

    imagepalettetotruecolor($im);

    $webp = imagewebp($im, str_replace('png', 'webp', $file));

}

imagedestroy($im);

PHP的版本是5.6


大话西游666
浏览 326回答 3
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 canvasimagecopy($im, $pngimg, 0, 0, 0, 0, $w, $h);// lastly, save canvas as a webpimagewebp($im, str_replace('png', 'webp', $file));// doneimagedestroy($im);&nbsp;&nbsp;编辑 1. *** 证明PHP GD 库依赖于 libgd 库。关联:https://github.com/libgd/libgd保存的相关代码(文件:gd_webp.c),显示对 Alpha 通道的尊重(当存在时):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; c = im->tpixels[y][x];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; a = gdTrueColorGetAlpha(c);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (a == 127) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; a = 0;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; a = 255 - ((a << 1) + (a >> 6));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; *(p++) = gdTrueColorGetRed(c);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; *(p++) = gdTrueColorGetGreen(c);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; *(p++) = gdTrueColorGetBlue(c);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; *(p++) = a;关于 static int _gdImageWebpCtx (gdImagePtr im, gdIOCtx * outfile, int quality)我提出的PHP代码依赖于一个事实,即阿尔法在GD库,因此确实推崇的作品,如果在以后的PHP版本测试不是您正在使用,特别是在我测试了7.3.0,但您的版本后,在早期的版本可能工作。

qq_花开花谢_0

您可能必须启用 Alpha 通道并保存它。也许试试这个:$ext = $type['ext'];if ($ext === 'jpg' || $ext === 'jpeg') {&nbsp; &nbsp; $im = imagecreatefromjpeg($file);&nbsp; &nbsp; $webp = imagewebp($im, str_replace($ext, 'webp', $file), 70);} elseif ($ext === 'png') {&nbsp; &nbsp; $im = imagecreatefrompng($file);&nbsp; &nbsp; imagepalettetotruecolor($im);&nbsp; &nbsp; imageAlphaBlending($im, true); // alpha channel&nbsp; &nbsp; imageSaveAlpha($im, true); // save alpha setting&nbsp; &nbsp; $webp = imagewebp($file, str_replace('png', 'webp', $file));}imagedestroy($im);PHP的版本是5.6

胡说叔叔

如果输出格式支持完全 alpha 透明度,则无需复制源图像。相反,在保存时告诉 GD 保留 alpha 通道就足够了:$im = imagecreatefrompng($infilename);imagesavealpha($im, true);imagewebp($im, $outfilename);
打开App,查看更多内容
随时随地看视频慕课网APP