"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Convert PNG to JPG with Compression and Preserve Transparency in PHP?

How to Convert PNG to JPG with Compression and Preserve Transparency in PHP?

Published on 2024-11-09
Browse:148

How to Convert PNG to JPG with Compression and Preserve Transparency in PHP?

Converting PNG to JPG with Compression in PHP

Many users seek to optimize their web applications by reducing the file size of images while maintaining visual quality. Converting high-quality PNG files to JPG is a common approach to achieve this as JPGs generally have smaller file sizes. PHP offers several functions and libraries to facilitate this conversion.

To safely convert a PNG to a JPG with a transparent background filled with white, the following PHP code can be utilized:

$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 the quality as needed (0 = lowest, 100 = highest)
imagejpeg($bg, $filePath . ".jpg", $quality);
imagedestroy($bg);

This code effectively converts a PNG image into a JPG format while ensuring that the transparency is accurately maintained. The adjustable quality parameter allows for fine-tuning the compression level to achieve the desired balance between file size and visual quality. The resulting JPG files can then be displayed on the web or utilized in other applications as required.

Latest tutorial More>

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