views:

43

answers:

3

I have a script that successfully creates thumbnails but they're rendered low quality. Is there something that I can change in the script to make the thumbnails better quality?

function createThumbnail($filename) {

    $final_width_of_image = 200;
    $path_to_image_directory = 'images/fullsized/';
    $path_to_thumbs_directory = 'images/thumbs/';

    if(preg_match('/[.](jpg)$/', $filename)) {
        $im = imagecreatefromjpeg($path_to_image_directory . $filename);
    } else if (preg_match('/[.](gif)$/', $filename)) {
        $im = imagecreatefromgif($path_to_image_directory . $filename);
    } else if (preg_match('/[.](png)$/', $filename)) {
        $im = imagecreatefrompng($path_to_image_directory . $filename);
    }

    $ox = imagesx($im);
    $oy = imagesy($im);

    $nx = $final_width_of_image;
    $ny = floor($oy * ($final_width_of_image / $ox));

    $nm = imagecreatetruecolor($nx, $ny);

    imagecopyresized($nm, $im, 0,0,0,0,$nx,$ny,$ox,$oy);

    if(!file_exists($path_to_thumbs_directory)) {
      if(!mkdir($path_to_thumbs_directory)) {
           die("There was a problem. Please try again!");
      }
       }

    imagejpeg($nm, $path_to_thumbs_directory . $filename);
    $tn = '<img src="' . $path_to_thumbs_directory . $filename . '" alt="image" />';
    $tn .= '<br />Congratulations. Your file has been successfully uploaded, and a thumbnail has been created.';
    echo $tn;   
}
+2  A: 

The only things I can suggest with this code are:

  • Increase the $final_width_of_image to make a larger thumbnail.
  • Add the third quality argument to imagejpeg; according to the PHP manual, it ranges from 0 to 100 with 100 being the best quality.
  • Don't use JPEG for your thumbnails.
  • Use imagecopyresampled to get a better pixel interpolation algorithm.
Borealid
Thanks! I changed it to `imagejpeg($nm, $path_to_thumbs_directory . $filename, 100);` I see a small difference in quality but `imagecopyresampled` really makes the difference! :) The script actually crops the original images using the zeros.
Cyber Junkie
Correction, it doesn't crop the image. Just changes the width :(
Cyber Junkie
+1  A: 

imagecopyresampled gives a lot better results (and do use the quality parameter of imagejpeg as already mentioned.

Wrikken
`imagecopyresampled` is awesome.
Cyber Junkie
A: 

Maybe try this code, which uses ImageCopyResampled:

function createImage($in_filename, $out_filename, $width, $height)
{
    $src_img = ImageCreateFromJpeg($in_filename);

    $old_x = ImageSX($src_img);
    $old_y = ImageSY($src_img);
    $dst_img = ImageCreateTrueColor($width, $height);
    ImageCopyResampled($dst_img, $src_img, 0, 0, 0, 0, $width, $height, $old_x, $old_y);

    ImageJpeg($dst_img, $out_filename, 80);

    ImageDestroy($dst_img);
    ImageDestroy($src_img);
}
gt
thanks I tried the function but I get a lot of errors :(
Cyber Junkie