我正在尝试使用gd库创建缩略图,但缩略图始终会变形.我想要的是从中心开始剪切图像,同时尊重新的分辨率并失去旧的比例.
我尝试过的
$im = ImageCreateFromJPEG($target_file);
$n_width = 500; // Fix the width of the thumb nail images
$n_height = 500; // Fix the height of the thumb nail imaage
$width = ImageSx($im); // Original picture width is stored
$height = ImageSy($im); // Original picture height is stored
$newimage = imagecreatetruecolor($n_width, $n_height);
imagecopyresampled($newimage, $im, 0, 0, 0, 0, $n_width, $n_height, $width, $height);
$thumb_target = $target_dir . $filename_without_ext . '-thumb.' . $params['file_ext'];
ImageJpeg($newimage, $thumb_target);
chmod("$thumb_target", 0777);
试图将imagecreatetruecolor更改为imagecrop,但仍不符合我想要的行为.
如果我不够清楚,请告诉我.
解决方法:
使用ImageManipulator库解决了它.在this answer找到了解决方案.
我的最终代码:
$im = new ImageManipulator($target_file);
$centreX = round($im->getWidth() / 2);
$centreY = round($im->getHeight() / 2);
$x1 = $centreX - 500;
$y1 = $centreY - 500;
$x2 = $centreX + 500;
$y2 = $centreY + 500;
$im->crop($x1, $y1, $x2, $y2);
$im->save($target_dir . $filename_without_ext . '-thumb.' . $params['file_ext']);