简体   繁体   中英

Converting PNG to JPEG file

I have a script to convert PNG files to JPEG files. Except, I'm not exactly sure how it works. What do use for $outputPngFile and $outputJpgFile? Can I do this with a tmp file, like when the user is uploading it? Then, how do I access the new file to move it to the proper image directory?

function pngTojpg($image, $outputPngFile, $outputJpgFile, $quality) {
$image = imagecreatefrompng($image);

//Save the png image
imagepng($image, $outputPngFile);         

//Save the jpeg image
imagejpeg($image, $outputJpgFile, $quality);

// Free up memory
imagedestroy($image);
}
<?php
$image = imagecreatefrompng('yourlocation/image.png');
imagejpeg($image, 'yournewlocation/image.jpg', 70);
imagedestroy($image);
?>

It would probably help you to know that you're using the GD library that has been bundled with PHP.

What the function is doing is taking a path to a png image ( $image ), loading it into a GD resource that can be manipulated within PHP ( imagecreatefrompng ), saving the image as a png to the png output path ( $outputPngFile ), then saving the image as a jpg to the jpg output path ( $outputJpgFile ) with a particular compression factor ( $quality ), and finally destroying the image resource object , since it isn't needed anymore.

Since it's saving the image as a png as well, the function was obviously intended to be used to save an image from either an external source (given by a URL) or temporary files from a user upload. You can do either, PHP doesn't care so long as the path you provide to the image file is valid.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM