Home > Backend Development > PHP Tutorial > How to Convert PNG to JPG with Compression in PHP?

How to Convert PNG to JPG with Compression in PHP?

Patricia Arquette
Release: 2024-11-02 22:07:03
Original
454 people have browsed it

How to Convert PNG to JPG with Compression in PHP?

Using PHP to Convert PNG to JPG with Compression

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>
Copy after login

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!

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