我在PHP中使用GD库有点问题 – 我调整图像大小,然后我想将其裁剪为320px(宽度)/ 240px(高度).让我说调整大小的图像是320px / 300px.当我裁剪时,图像底部会出现1-px黑条 – 我不知道为什么.
我正在使用imagecrop,imagecreatefromjpeg和imagecopyresampled
这是一个例子:
谢谢你的时间.
代码
$filename = '../store/projects/project-123.jpg';
$mime = mime_content_type($filename);
list($w, $h) = getimagesize($filename);
$prop = $w / $h;
$new_w = 0;
$new_h = 0;
if ($prop <= 4/3) {
$new_w = 320;
$new_h = (int)floor($h*($new_w/$w));
} else {
$new_h = 240;
$new_w = (int)floor($w*($new_h/$h));
}
$thumb = imagecreatetruecolor($new_w, $new_h);
if (strcmp($mime,'image/png') == 0) {
header('Content-Type: image/png');
$source = imagecreatefrompng($filename);
} else {
header('Content-Type: image/jpeg');
$source = imagecreatefromjpeg($filename);
}
imagecopyresampled($thumb, $source, 0, 0, 0, 0, $new_w, $new_h, $w, $h);
$filename = '../store/projects-thumbs/project-123.jpg';
$crop_data = array('x' => 0 , 'y' => 0, 'width' => 320, 'height'=> 240);
$thumb = imagecrop($thumb, $crop_data);
imagejpeg($thumb, $filename, 100);
imagedestroy($thumb);
imagedestroy($source);
解决方法:
imagecrop()有一个known bug,可以添加黑色底部边框.
您可以使用imagecopyresized()解决此问题.请参阅my answer至另一个SO question,询问imagecrop()替代方案.