问题
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);
}
回答1:
<?php
$image = imagecreatefrompng('yourlocation/image.png');
imagejpeg($image, 'yournewlocation/image.jpg', 70);
imagedestroy($image);
?>
回答2:
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.
来源:https://stackoverflow.com/questions/14220191/converting-png-to-jpeg-file