简体   繁体   English

PHP-GD图像调整大小会丢失图像质量

[英]PHP-GD Image re-size loses the quality of the image

I've made this piece of code, it will re-size images on the fly, if it can't find the requested image, and then stores it. 我编写了这段代码,如果找不到所需的图像,它将即时调整图像大小,然后将其存储。

The only problem with this is that the output jpg image has a low quality. 唯一的问题是输出的jpg图像质量较低。

I was wondering if there is something I need to change to improve the image quality. 我想知道是否需要更改某些东西以改善图像质量。

if (isset($_GET['size'])) {
    $size = $_GET['size'];
}

if (isset($_GET['name'])) {
    $filename = $_GET['name'];
}

$filePath = "files/catalog/" . urldecode($filename);

// Content type

header('Content-Type: image/jpeg');

// Get new sizes
list($width, $height) = getimagesize($filePath);

if ($_GET["name"] && !$size) {
    $newwidth  = $width * $percent;
    $newheight = $height * $percent;

} else if ($_GET["name"] && $size) {
    switch ($size) {
        case "thumbs":
            $newwidth  = 192;
            $newheight = 248;
            break;
        case "large":
            $newwidth  = 425;
            $newheight = 550;
            break;
    }
}

$resizedFileName = $filename; 
$resizedFileName = str_replace(".jpg", "", $resizedFileName) . ".jpg";
$resizedFilePath = "files/catalog/" . urldecode($resizedFileName);


if (!file_exists($resizedFilePath)) {
    // Load
    $thumb  = imagecreatetruecolor($newwidth, $newheight);
    $source = imagecreatefromjpeg($filePath);

    // Resize
    imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

    // Output
    imagejpeg($thumb, $resizedFilePath);
    //file_put_contents($, $binarydata);

    $imageContent = file_get_contents($resizedFilePath);
    echo $imageContent;

} else {
    $imageContent = file_get_contents($resizedFilePath);
    echo $imageContent;
}

代替imagecopyresize(),必须使用imagecopyresampled(),并且imagejpeg()函数具有第三个可选参数,并且可以指定质量。

可能是因为您使用的imagejpeg()错误,所以函数中的第二个变量代表质量百分比!

You want imagecopyresampled() . 您需要imagecopyresampled() resize works by throwing away unecessary pixels. 通过丢弃不必要的像素来调整大小。 resampled() will average things out and produce much smoother results. resampled()将使结果平均,并产生更平滑的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM