Steven Sacradoor
Steven Sacradoor

Reputation: 253

How can I convert all images to jpg?

I have script:

<?php

include('db.php');
session_start();
$session_id = '1'; // User session id
$path = "uploads/";

$valid_formats = array("jpg", "png", "gif", "bmp", "jpeg");
if (isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST") {
    $name = $_FILES['photoimg']['name'];
    $size = $_FILES['photoimg']['size'];
    if (strlen($name)) {
        list($txt, $ext) = explode(".", $name);
        if (in_array($ext, $valid_formats)) {
            if ($size < (1024 * 1024)) { // Image size max 1 MB
                $actual_image_name = time() . $session_id . "." . $ext;
                $tmp = $_FILES['photoimg']['tmp_name'];
                if (move_uploaded_file($tmp, $path . $actual_image_name)) {
                    mysql_query("UPDATE users SET profile_image='$actual_image_name' WHERE uid='$session_id'");
                    echo "<img src='uploads/" . $actual_image_name . "' class='preview'>";
                } else {
                    echo "failed";
                }
            } else {
                echo "Image file size max 1 MB";
            }
        } else {
            echo "Invalid file format..";
        }
    } else {
        echo "Please select image..!";
    }
    exit;
}

?>

Is possible convert all images (png, gif etc) to jpg with 100% quality? If yes, how? I would like allow to upload png and gif, but this script should convert this files to jpg. Is possible this with PHP?

Upvotes: 14

Views: 63160

Answers (6)

Lucas Bustamante
Lucas Bustamante

Reputation: 17168

Davide Berra's answer is great, so I improved the file type detection a little, using exif_imagetype() instead of relying on the file extension:

/**
*   Auxiliar function to convert images to JPG
*/
function convertImage($originalImage, $outputImage, $quality) {

    switch (exif_imagetype($originalImage)) {
        case IMAGETYPE_PNG:
            $imageTmp=imagecreatefrompng($originalImage);
            break;
        case IMAGETYPE_JPEG:
            $imageTmp=imagecreatefromjpeg($originalImage);
            break;
        case IMAGETYPE_GIF:
            $imageTmp=imagecreatefromgif($originalImage);
            break;
        case IMAGETYPE_BMP:
            $imageTmp=imagecreatefrombmp($originalImage);
            break;
        // Defaults to JPG
        default:
            $imageTmp=imagecreatefromjpeg($originalImage);
            break;
    }

    // quality is a value from 0 (worst) to 100 (best)
    imagejpeg($imageTmp, $outputImage, $quality);
    imagedestroy($imageTmp);

    return 1;
}

You must have php_exif extension enabled to use this.

Upvotes: 8

Anton Moskalenko
Anton Moskalenko

Reputation: 1

From PhpTools:

/**
 * @param string $source (accepted jpg, gif & png filenames)
 * @param string $destination
 * @param int $quality [0-100]
 * @throws \Exception
 */
public function convertToJpeg($source, $destination, $quality = 100) {

    if ($quality < 0 || $quality > 100) {
        throw new \Exception("Param 'quality' out of range.");
    }

    if (!file_exists($source)) {
        throw new \Exception("Image file not found.");
    }

    $ext = pathinfo($source, PATHINFO_EXTENSION);

    if (preg_match('/jpg|jpeg/i', $ext)) {
        $image = imagecreatefromjpeg($source);
    } else if (preg_match('/png/i', $ext)) {
        $image = imagecreatefrompng($source);
    } else if (preg_match('/gif/i', $ext)) {
        $image = imagecreatefromgif($source);
    } else {
        throw new \Exception("Image isn't recognized.");
    }

    $result = imagejpeg($image, $destination, $quality);

    if (!$result) {
        throw new \Exception("Saving to file exception.");
    }

    imagedestroy($image);
}

Upvotes: 0

Ahmad Vaqas Khan
Ahmad Vaqas Khan

Reputation: 658

A small code to convert image.png to image.jpg at desired image quality:

<?php
$image = imagecreatefrompng('image.png');
imagejpeg($image, 'image.jpg', 70); // 0 = worst / smaller file, 100 = better / bigger file 
imagedestroy($image);
?>

Upvotes: 3

Roy B. xSITE
Roy B. xSITE

Reputation: 141

a small fix to davide's answer, the correct function for converting from BMP is "imagecreatefromwbmp" instead of imagecreatefrombmp (missing "w") also you should consider that png may be transparent, here is a way to fill it with white BG (jpeg can't apply alpha data).

function convertImage($originalImage, $outputImage, $quality){
// jpg, png, gif or bmp?
$exploded = explode('.',$originalImage);
$ext = $exploded[count($exploded) - 1]; 
if (preg_match('/jpg|jpeg/i',$ext)){$imageTmp=imagecreatefromjpeg($originalImage);}
else if (preg_match('/png/i',$ext)){$imageTmp=imagecreatefrompng($originalImage);}
else if (preg_match('/gif/i',$ext)){$imageTmp=imagecreatefromgif($originalImage);}
else if (preg_match('/bmp/i',$ext)){$imageTmp=imagecreatefromwbmp($originalImage);}
else    {    return false;}
// quality is a value from 0 (worst) to 100 (best)
imagejpeg($imageTmp, $outputImage, $quality);
imagedestroy($imageTmp);
return true;
}

Upvotes: 1

Davide Berra
Davide Berra

Reputation: 6568

Try this code: originalImage is the path of... the original image... outputImage is self explaining enough. Quality is a number from 0 to 100 setting the output jpg quality (0 - worst, 100 - best)

function convertImage($originalImage, $outputImage, $quality)
{
    // jpg, png, gif or bmp?
    $exploded = explode('.',$originalImage);
    $ext = $exploded[count($exploded) - 1]; 

    if (preg_match('/jpg|jpeg/i',$ext))
        $imageTmp=imagecreatefromjpeg($originalImage);
    else if (preg_match('/png/i',$ext))
        $imageTmp=imagecreatefrompng($originalImage);
    else if (preg_match('/gif/i',$ext))
        $imageTmp=imagecreatefromgif($originalImage);
    else if (preg_match('/bmp/i',$ext))
        $imageTmp=imagecreatefrombmp($originalImage);
    else
        return 0;

    // quality is a value from 0 (worst) to 100 (best)
    imagejpeg($imageTmp, $outputImage, $quality);
    imagedestroy($imageTmp);

    return 1;
}

Upvotes: 49

chill0r
chill0r

Reputation: 1129

Try using Imagick setImageFormat, for me it provides the best image quality
http://php.net/manual/en/imagick.setimageformat.php

$im = new imagick($image);

// convert to png
$im->setImageFormat('png');

//write image on server
$im->writeImage($image .".png");
$im->clear();
$im->destroy(); 

Upvotes: 11

Related Questions