0
votes

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.

Exaple Image

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);
2
Have you tried to use imagecopyresampled instead of imagecopyresized ? - Marcin Nabiałek
no i have'nt tried .. but is imagecopyresized differs.. ? - Bhavesh G
It often makes the result is better and images are smoother than using imagecopyresized - Marcin Nabiałek

2 Answers

2
votes

Using imagecopyresampled() function instead of imagecopyresized() often makes the rendered image smoother, so in this case probably it will be the solution.

0
votes

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.