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

I want to write a procedure that takes a PNG image path as a parameter and convert this image to an 8-bit PNG image. For this I need to use the PHP GD library.

+6
source share
2 answers

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

convertPNGto8bitPNG () function

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 the PNG source file
  • $ destPath - Path to destination PNG file.

Using

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

Example (original โ†’ 8 bit)

(Source: pfc.png) ORIGINAL PNG IMAGE

enter image description here

(Purpose: pfc8bit.png) PNG CONVERTED IMAGE (8 bits)

enter image description here


Note. I have not tried this feature with transparent images. I think it works, but I'm not 100% sure.

Hope this helps.

+11
source

Instead of the GD library, I highly recommend using pngquant 1.5+ with the exec() or popen() functions.

The GD library has a very poor palette generation format.

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

enter image description here

pngquant supports alpha transparency very well.

+8
source

Source: https://habr.com/ru/post/886449/


All Articles