Use PHP to convert PNG to JPG with compression?

John picture John · Jul 29, 2009 · Viewed 117.9k times · Source

I have a bunch of high quality PNG files. I want to use PHP to convert them to JPG because of it's smaller file sizes while maintaining quality. I want to display the JPG files on the web.

Does PHP have functions/libraries to do this? Is the quality/compression any good?

Answer

Daniel De León picture Daniel De León · Jan 21, 2012

Do this to convert safely a PNG to JPG with the transparency in white.

$image = imagecreatefrompng($filePath);
$bg = imagecreatetruecolor(imagesx($image), imagesy($image));
imagefill($bg, 0, 0, imagecolorallocate($bg, 255, 255, 255));
imagealphablending($bg, TRUE);
imagecopy($bg, $image, 0, 0, 0, 0, imagesx($image), imagesy($image));
imagedestroy($image);
$quality = 50; // 0 = worst / smaller file, 100 = better / bigger file 
imagejpeg($bg, $filePath . ".jpg", $quality);
imagedestroy($bg);