Search code examples
phpimagecompressionimage-compression

PHP Reducing all image types quality


I am looking for a library that can reduce all image types quality (PNG, GIF and JPEG).
I know that I can reduce JPEG using imagejpeg()
I also know that I can reduce PNG using imagepng() although this is not powerful enough.

I need something that can convert PNG 24 to PNG8 without removing the alpha.

Can't use ImageMagick since I cannot install anything on my server.

EDIT:
I also need something that can convert from 32 bit to 8 (which I am pretty sure is the same like from 32)

Found the soultion here

Thanks


Solution

  • 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 Usage

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