Converting PNG to JPG with Compression in PHP
Question:
Seeking a method to convert PNG images to JPG in PHP while preserving quality and minimizing file size. How can this be achieved?
Answer:
PHP provides an image manipulation library that allows for easy conversion between image formats. Here's how to convert a PNG file to JPG with compression:
<code class="php">// Convert PNG image to JPG with 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); // Set compression quality (0=worst, 100=best) $quality = 50; // Convert to JPG and save to new file imagejpeg($bg, $filePath . ".jpg", $quality); imagedestroy($bg);</code>
This code:
The above is the detailed content of How can I convert PNG images to JPG with compression in PHP while preserving quality and minimizing file size?. For more information, please follow other related articles on the PHP Chinese website!