Home » Php » Convert JPG/GIF image to PNG in PHP?

Convert JPG/GIF image to PNG in PHP?

Posted by: admin April 23, 2020 Leave a comment

Questions:

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?

How to&Answers:

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.

Answer:

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); 

Answer:

<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';
    }       
}
?>

Answer:

Very simple using the gd functions:

switch (exif_imagetype($image)) {
    case IMAGETYPE_GIF :
        $img = imagecreatefromgif($image);
        break;
    case IMAGETYPE_JPEG :
        $img = imagecreatefromjpeg($image);
        break;
    default :
        throw new InvalidArgumentException('Invalid image type');
}

imagepng($img, $filename);

For conciseness this obviously doesn’t handle the case if the image is already a PNG.