质量更好的缩略图

时间:2010-08-02 15:06:19

标签: php image thumbnails

我有一个成功创建缩略图的脚本,但它们的质量很低。是否有一些我可以在脚本中更改以使缩略图更好的质量?

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;   
}

3 个答案:

答案 0 :(得分:5)

我可以使用此代码建议的唯一内容是:

  • 增加$final_width_of_image以制作更大的缩略图。
  • 将第三个quality参数添加到imagejpeg;根据{{​​3}},它的范围从0到100,其中100是最好的质量。
  • 请勿使用JPEG作为缩略图。
  • 使用imagecopyresampled获得更好的像素插值算法。

答案 1 :(得分:1)

imagecopyresampled可以提供更好的结果(并且如前所述使用imagejpeg的质量参数。

答案 2 :(得分:1)

也许尝试使用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);
}