简体   繁体   中英

PHP GD thumbnail generation image pixels distorted

I've php script to generate thumbnails on images upload, using PHP GD Library.

The height of the thumbnail is fixed ( in this case its 240px ), and its width will be calculated according to original image's aspect ratio. ex.

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

but in some images the output thumbnail image having pixels distorted. Below images addresses my question clearly.

实例图片

After generating thumbnail the output image ( Left ), but i want the output image as it is in Right

My Code :

$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()通常会使渲染的图像更平滑,因此在这种情况下,可能是解决方案。

Used imagecopyresampled instead of imagecopyresized done the trick ..

Reason :

imagecopyresized will copy and scale and image. This uses a fairly primitive algorithm that tends to yield more pixelated results.

imagecopyresampled will copy and scale and image, it uses a smoothing and pixel interpolating algorithm that will generally yield much better results then imagecopyresized at the cost of a little cpu usage.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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