How to convert PNG to 8-bit PNG using PHP GD library

牧云@^-^@ 提交于 2019-11-29 14:27:48

问题


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.


回答1:


To convert any PNG image to 8-bit PNG use this function, I've just created

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

 }

Parameters

  • $sourcePath - Path to source PNG file
  • $destPath - Path to destination PNG file

Note

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.

Usage

convertPNGto8bitPNG ('pfc.png', 'pfc8bit.png');

Example (original -> 8-bit)

(Source: pfc.png) ORIGINAL PNG IMAGE

(Destination: pfc8bit.png) CONVERTED PNG IMAGE (8-bit)

Hope someone finds this helpful.




回答2:


Instead of GD library I strongly recommend using pngquant 1.5+ commandline using exec() or popen() functions.

GD library has very poor-quality palette generation code.

Same image as in the other answer, same file size as GD library, but converted using pngquant to merely 100 colors (not even 256):

pngquant supports alpha transparency very well.



来源:https://stackoverflow.com/questions/5752514/how-to-convert-png-to-8-bit-png-using-php-gd-library

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!