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

Jor*_*ana 5 php wordpress image

我需要将图像(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);
Run Code Online (Sandbox Code Playgroud)

PHP的版本是5.6

Get*_*Set 6

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

Run Code Online (Sandbox Code Playgroud)

编辑 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;
Run Code Online (Sandbox Code Playgroud)

关于 static int _gdImageWebpCtx (gdImagePtr im, gdIOCtx * outfile, int quality)

我提出的PHP代码依赖于一个事实,即阿尔法在GD库,因此确实推崇的作品,如果在以后的PHP版本测试不是您正在使用,特别是在我测试了7.3.0,但您的版本后,在早期的版本可能工作。