如何将所有图像转换为jpg?

时间:2013-01-27 16:30:15

标签: php image-processing

我有脚本:

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

?>

是否可以将所有图像(png,gif等)转换为质量为100%的jpg?如果有,怎么样?我想允许上传png和gif,但是这个脚本应该将这些文件转换为jpg。可以用PHP吗?

6 个答案:

答案 0 :(得分:37)

试试这段代码:originalImage是......原始图片的路径... outputImage足够自我解释。 Quality是从0到100的数字,设置输出jpg质量(0 - 最差,100 - 最佳)

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

答案 1 :(得分:8)

尝试使用Imagick setImageFormat,对我而言,它可以提供最佳的图像质量 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(); 

答案 2 :(得分:3)

以所需图像质量将image.png转换为image.jpg的小代码:

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

答案 3 :(得分:3)

Davide Berra的答案很棒,所以我使用 exif_imagetype()改进了文件类型检测,而不是依赖于文件扩展名:

/**
*   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;
}

您必须启用 php_exif 扩展程序才能使用此功能。

答案 4 :(得分:1)

davide答案的一个小修正,从BMP转换的正确功能是“imagecreatefrom w bmp”而不是imagecreatefrombmp(缺少“w”) 另外你应该考虑png可能是透明的,here is用白色BG填充它(jpeg不能应用alpha数据)。

public string GetStringContent()
{
    string[] myStrings = { "I want to take this string", "This is not interesting" };
    string strContent=string.Empty;
    for (int i = 0; i < myStrings.Length; i++)
    {
        if (myStrings[i].Contains("want"))
        {
            strContent = myStrings[i];
            break;
        }
    }
    return strContent;
} 

答案 5 :(得分:0)

来自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);
}