Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

png

png-8

gdlib

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.

like image 986
Nilesh Avatar asked Apr 22 '11 05:04

Nilesh


1 Answers

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

enter image description here

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

enter image description here

Hope someone finds this helpful.

like image 105
Wh1T3h4Ck5 Avatar answered Nov 08 '22 23:11

Wh1T3h4Ck5