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.