Home > Article > Backend Development > How to Convert PNG to JPG with Compression in PHP?
PHP can handle image manipulation tasks through its built-in functions and libraries. One sought-after feature is the ability to convert high-quality PNG images to smaller JPG files. This transformation is desirable for web display due to JPG's efficient file size while preserving visual quality.
PHP offers several image processing libraries. For PNG-to-JPG conversion, one popular method is to employ the GD library (Graphics Draw). This library allows you to load, manipulate, and save images using functions like imagecreatefrompng(), imagecreatetruecolor(), and imagejpeg().
To ensure the conversion maintains image quality and transparency, consider the following steps:
<code class="php">$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; // Adjust quality from 0 (worst) to 100 (best) imagejpeg($bg, $filePath . ".jpg", $quality); imagedestroy($bg);</code>
In this code, $image represents the original PNG image. The new JPG image is created with a white background ($bg) and the PNG image is copied onto it, preserving transparency. The $quality parameter controls the JPG compression level, with lower values producing smaller but less detailed images. By carefully adjusting this parameter, you can strike a balance between file size and visual fidelity.
The above is the detailed content of How to Convert PNG to JPG with Compression in PHP?. For more information, please follow other related articles on the PHP Chinese website!