Use PHP to convert PNG to JPG with compression? Use PHP to convert PNG to JPG with compression? php php

Use PHP to convert PNG to JPG with compression?


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


Be careful of what you want to convert. JPG doesn't support alpha-transparency while PNG does. You will lose that information.

To convert, you may use the following function:

// Quality is a number between 0 (best compression) and 100 (best quality)function png2jpg($originalFile, $outputFile, $quality) {    $image = imagecreatefrompng($originalFile);    imagejpeg($image, $outputFile, $quality);    imagedestroy($image);}

This function uses the imagecreatefrompng() and the imagejpeg() functions from the GD library.


This is a small example that will convert 'image.png' to 'image.jpg' at 70% image quality:

<?php$image = imagecreatefrompng('image.png');imagejpeg($image, 'image.jpg', 70);imagedestroy($image);?>

Hope that helps