繁体   English   中英

PHP GD缩略图生成图像像素变形

[英]PHP GD thumbnail generation image pixels distorted

我已经使用PHP GD Library使用php脚本来生成图像上传缩略图。

缩略图的高度是固定的(在本例中为240px ),其宽度将根据原始图像的长宽比进行计算。 例如

$new_height = $thumbHeight;
$new_width = intval($thumbHeight * $width / $height);

但在某些图像中,输出缩略图的像素失真。 下图清楚地说明了我的问题。

实例图片

生成缩略图后,输出图像( Left ),但是我希望输出图像如右图所示

我的代码:

$file = "pic.jpg";
$thumbHeight = 240;
$progressive = false;

    $img;
    if(preg_match('/[.](jpg)$/', $file)) {
        $img = imagecreatefromjpeg($file);
    } else if (preg_match('/[.](gif)$/', $file)) {
        $img = imagecreatefromgif($file);
    } else if (preg_match('/[.](png)$/', $file)) {
        $img = imagecreatefrompng($file);
    } else  if(preg_match('/[.](jpeg)$/', $file)) {
        $img = imagecreatefromjpeg($file);
    }

$arr_image_details = getimagesize($file);
$width = $arr_image_details[0]; // width of input image
$height = $arr_image_details[1]; // height of input image

$new_height = $thumbHeight;    // new thumbnail height 
$new_width = intval($thumbHeight * $width / $height);  // new thumbnail width


$tmp_img = imagecreatetruecolor( $new_width, $new_height );
imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
if($progressive) imageinterlace($tmp_img, 1); 
imagejpeg( $tmp_img, "lag-$file",100 ); 

imagedestroy($img);
imagedestroy($tmp_img);

使用imagecopyresampled()函数而不是imagecopyresized()通常会使渲染的图像更平滑,因此在这种情况下,可能是解决方案。

使用imagecopyresampled而不是imagecopyresized可以解决问题。

原因:

imagecopyresized将复制并缩放图像。 这使用了相当原始的算法,往往会产生更多的像素化结果。

imagecopyresampled将复制,缩放和图像,它使用平滑和像素插值算法,通常会产生更好的结果,然后以少量cpu使用为代价对imagecopyresize进行调整。

暂无
暂无

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

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