Home > Article > Backend Development > How to Convert PNG to JPG with PHP While Maintaining Quality and Transparency?
How to Convert PNG to JPG with PHP Preserving Quality
Many websites prefer JPG images due to their reduced file size without compromising visual quality. If you have a collection of PNG files and need to convert them to JPG using PHP, here's a comprehensive guide:
PHP Functions and Libraries for PNG to JPG Conversion
PHP offers several functions and libraries that efficiently handle image manipulation.
imagecreatefrompng(): Reads a PNG file and creates an image resource.
imagejpeg(): Outputs a JPG image from an image resource.
imagecopy(): Copies a portion of one image onto another.
imagedestroy(): Frees memory associated with an image resource.
Conversion Code Snippet
To safely convert PNG to JPG with transparency in white, follow these 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; // 0 = worst / smaller file, 100 = better / bigger file imagejpeg($bg, $filePath . ".jpg", $quality); imagedestroy($bg);</code>
The above is the detailed content of How to Convert PNG to JPG with PHP While Maintaining Quality and Transparency?. For more information, please follow other related articles on the PHP Chinese website!