问题
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;
}
回答1:
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 toimagejpeg
; 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.
回答2:
imagecopyresampled
gives a lot better results (and do use the quality parameter of imagejpeg
as already mentioned.
回答3:
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);
}
来源:https://stackoverflow.com/questions/3389036/better-quality-thumbnails