Possible Duplicate of
Convert jpg image to gif, png & bmp format using PHP
I have a PHP form that allows image uploads and checks exif_imagetype();
to make sure an image is valid.
However, I want all formats, PNG, JPG, JPEG, and GIF, to end up being PNG once submitted.
How can I go about doing this?
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.
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.
<form method="post" enctype="multipart/form-data">
<input type="file" name="image" />
<input type="submit" name="submit" value="Submit" />
</form>
<?php
if(isset($_POST['submit']))
{
if(exif_imagetype($_FILES['image']['tmp_name']) == IMAGETYPE_GIF)
{
$newpng = 'image.png';
$png = imagepng(imagecreatefromgif($_FILES['image']['tmp_name']), $newpng);
}
elseif(exif_imagetype($_FILES['image']['tmp_name']) == IMAGETYPE_JPEG)
{
$newpng = 'image.png';
$png = imagepng(imagecreatefromjpeg($_FILES['image']['tmp_name']), $newpng);
}
else //already png
{
$newpng = 'image.png';
}
}
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With