如何使用PHP GD库将PNG转换为8位PNG

Nil*_*esh 7 php png gdlib png-8

我想写一个例程,它将PNG图像路径作为参数,并将该图像转换为8位PNG图像.我需要使用PHP GD库.

Wh1*_*Ck5 12

要将任何PNG图像转换为8位PNG,请使用此功能,我刚创建

函数convertPNGto8bitPNG()

 function convertPNGto8bitPNG ($sourcePath, $destPath) {

     $srcimage = imagecreatefrompng($sourcePath);
     list($width, $height) = getimagesize($sourcePath);

     $img = imagecreatetruecolor($width, $height);
     $bga = imagecolorallocatealpha($img, 0, 0, 0, 127);
     imagecolortransparent($img, $bga);
     imagefill($img, 0, 0, $bga);
     imagecopy($img, $srcimage, 0, 0, 0, 0, $width, $height);
     imagetruecolortopalette($img, false, 255);
     imagesavealpha($img, true);

     imagepng($img, $destPath);
     imagedestroy($img);

 }
Run Code Online (Sandbox Code Playgroud)

参数

  • $ sourcePath - 源PNG文件的路径
  • $ destPath - 目标PNG文件的路径

注意

我建议在运行此代码之前确保$sourcePath存在且$destPath可写.也许此功能不适用于某些透明图像.

用法

convertPNGto8bitPNG ('pfc.png', 'pfc8bit.png');
Run Code Online (Sandbox Code Playgroud)

示例(原始 - > 8位)

(来源:pfc.png)原始的PNG图像

在此输入图像描述

(目的地:pfc8bit.png)CONVERTED PNG IMAGE(8位)

在此输入图像描述

希望有人觉得这很有帮助.


Kor*_*nel 9

而不是GD库我强烈建议使用pngquant 1.5+命令行使用exec()popen()功能.

GD库具有非常差的调色板生成代码.

与其他答案中的图像相同,文件大小与GD库相同,但pngquant仅使用100种颜色(甚至不是256种)进行转换:

在此输入图像描述

pngquant非常支持alpha透明度.