如何使用PHP GD库将PNG转换为8位PNG
问题描述:
我想编写一个例程,该例程将PNG图像路径作为参数并将该图像转换为8位PNG图像.我需要为此使用PHP GD库.
I want to write a routine which takes PNG image path as parameter and convert that image into 8-bit PNG image. I need to use PHP GD library for this.
答
要使用此功能将任何PNG图像转换为8位PNG,我刚刚创建了
To convert any PNG image to 8-bit PNG use this function, I've just created
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);
}
参数
- $ sourcePath -源PNG文件的路径
- $ destPath -目标PNG文件的路径
- $sourcePath - Path to source PNG file
- $destPath - Path to destination PNG file
Parameters
我建议在运行此代码之前确保$sourcePath
存在并且$destPath
可写.也许此功能不适用于某些透明图像.
I recommend to make sure that $sourcePath
exists and $destPath
is writable before running this code. Maybe this function won't work with some transparent images.
convertPNGto8bitPNG ('pfc.png', 'pfc8bit.png');
示例(原始-> 8位)
(来源:pfc.png)原始PNG图像
(目标:pfc8bit.png)已转换的PNG图像(8位)
(Destination: pfc8bit.png) CONVERTED PNG IMAGE (8-bit)
希望有人发现这有帮助.
Hope someone finds this helpful.