Home > Article > Backend Development > How to convert png to jpg in php
Everyone should be aware that jpg format images tend to have a higher compression rate than png format images. Therefore, under normal circumstances, we prefer users to use png format images instead of jpg format.
But we often cannot restrict users from using jpg format images or using jpg format images, so all we can do is to use certain means to convert them after the user has uploaded them.
First of all, if you want to use the image conversion function in php, you must install the relevant php library, which is the commonly used gd library. The way to check if the gd library is installed in your php environment is simple. Just run phpinfo().
Okay, let’s talk about how to convert png format images into jpg format images.
The first step: Convert the image into a file code
$png = imagecreatefrompng($filePath);
If the execution fails, return false;
The second step: Convert the file code into a jpg format image
imagejpeg($png, $newfilepath, 75);
Here is a general explanation. The last parameter means the converted quality, and the value is between 0 and 100.
If the function fails to execute, it will also return false;
Step 3: Release the file code
imagedestroy($png);
Please note that this step must not be omitted, otherwise memory leaks will occur .
Related references:php中文网
The above is the detailed content of How to convert png to jpg in php. For more information, please follow other related articles on the PHP Chinese website!