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

Susan Sarandon
Release: 2024-11-01 23:48:29
Original
529 people have browsed it

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:

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

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.

The above is the detailed content of How to Convert PNG to JPG with Compression and Preserve Transparency in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!