Tuesday, January 3

PHP – how to Convert JPG-GIF image to PNG?


PHP – how to Convert JPG-GIF image to PNG formart

In this post we will show you how to JPG-GIF image to PNG in php . hear we use imagepng() for conver image formart.

How to use it imagepng()::

imagepng(imagecreatefromstring(file_get_contents($filename)), "output.png");

You would use $_FILES["user_image"]["tmp_name"] for the user_image(for get file name from user), and a different output user_image obviously. But the image format probing itself become redundant.

Method :: 1 # Convert JPG/GIF image to PNG using if-else

 <!-- Convert JPG/GIF image to PNG --->
<form method="post" enctype="multipart/form-data">
    <p>Convert JPG/GIF image to PNG</p><br>
    <input type="file" name="user_image" /><br>
    <input type="submit" name="submit" value="Submit" />
</form>

<?php
// submit button press/hit
if(isset($_POST['submit']))
{
    if(exif_imagetype($_FILES['user_image']['tmp_name']) ==  IMAGETYPE_GIF)
    {
        // Convert GIF to png image type
        $new_png_img = 'user_image.png';
        $png_img = imagepng(imagecreatefromgif($_FILES['user_image']['tmp_name']), $new_png_img);
    }
    elseif(exif_imagetype($_FILES['user_image']['tmp_name']) ==  IMAGETYPE_JPEG)
    {
        // Convert JPG/JPEG to png image type
        $new_png_img = 'user_image.png';
        $png_img = imagepng(imagecreatefromjpeg($_FILES['user_image']['tmp_name']), $new_png_img);
    }
    else
    {
        // already png image type
        $new_png_img = 'user_image.png';
    }      
}
?>

 

Method :: 2 # Convert JPG/GIF image to PNG using switch case

 

<!-- Convert JPG/GIF image to PNG --->
<form method="post" enctype="multipart/form-data">
    <p>Convert JPG/GIF image to PNG</p><br>
    <input type="file" name="user_image" /><br>
    <input type="submit" name="submit" value="Submit" />
</form>

<?php
// submit button press/hit
if(isset($_POST['submit']))
{
    $conver_image = $_FILES['user_image']['tmp_name'];
    $extension = pathinfo($conver_image, PATHINFO_EXTENSION);
    switch ($extension) {
        case 'jpg':
        case 'jpeg':
           $set_image = imagecreatefromjpeg($conver_image);
        break;
        case 'gif':
           $set_image = imagecreatefromgif($conver_image);
        break;
        case 'png':
           $set_image = imagecreatefrompng($conver_image);
        break;
    }

    imagepng($set_image, $new_conver_image);
}
?>



No comments:

Post a Comment

10 Best Chatting Apps In India

  The modern world is all about Internet. There was a time when people use to pay high telephone bills to stay in touch with their friends a...