我在使用 PHP 中的 GD 库时遇到一个小问题 - 我调整图像大小,然后我想将其裁剪为 320 像素(宽度)/240 像素(高度)。让我说调整大小的图像是 320px/300px。当我裁剪它时,图像底部会出现一个 1 像素的黑色 strip - 我不知道为什么。
我正在使用 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()
替代方法。
关于PHP:使用 GD 库时图像上出现黑条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27471725/