Convert JPG/GIF image to PNG in PHP?
Based on what kind of image it is you could select the correct function to open the file:
$extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
switch ($extension) {
case 'jpg':
case 'jpeg':
$image = imagecreatefromjpeg($filename);
break;
case 'gif':
$image = imagecreatefromgif($filename);
break;
case 'png':
$image = imagecreatefrompng($filename);
break;
}
Then you just save the file using:
imagepng($image, $new_filename, $quality);
It might be worth noting that this will only parse the actual extension and not really validate so the file is in the specific format. For instance, you could take a jpg image and just change the extension to png.
So a better approach is to use the exif_imagetype()
which will return the type of image not depending on the actual extension.
You just need imagepng()
then. In fact it almost becomes a one-liner:
imagepng(imagecreatefromstring(file_get_contents($filename)), "output.png");
You would use $_FILES["id"]["tmp_name"]
for the filename, and a different output filename obviously. But the image format probing itself would become redundant.