Aaron
Aaron

Reputation: 1986

Convert JPG/GIF image to PNG in PHP?

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?

Upvotes: 42

Views: 99427

Answers (4)

Cyclonecode
Cyclonecode

Reputation: 30131

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.

Upvotes: 16

Zul
Zul

Reputation: 3608

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

Upvotes: 6

mario
mario

Reputation: 145512

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.

Upvotes: 105

deceze
deceze

Reputation: 522597

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.

Upvotes: 3

Related Questions