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:
$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);
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3