这是我的代码,但我不知道为什么,但是当我上传垂直图像时,它会调整大小并且我会在两侧看到两条黑色条纹。对于宽图像,它在大多数时间都能很好地工作,但是对于一些图像,我也会得到黑色条纹。我该如何解决?
我的目的是裁剪每个图像,水平只是一个提示以适合我的盒子,垂直我想裁剪,所以宽度是相同的,它们没有被切割的顶部和底部。
$thumb_height = 200;
$thumb_width = 300;
$thumb = imagecreatetruecolor($thumb_width, $thumb_height);
if($width >= $height) {
// If image is wider than thumbnail (in aspect ratio sense)
$new_height = $thumb_height;
$new_width = $width / ($height / $thumb_height);
} else {
// If the thumbnail is wider than the image
$new_width = $thumb_width;
$new_height = $height / ($width / $thumb_width);
}
$output_filename_mid = 'uploads/'.IMG_L.$fileName;
imagecopyresampled($thumb,
$image,
0 - ($new_width - $thumb_width) / 2, // Center the image horizontally
0 - ($new_height - $thumb_height) / 2, // Center the image vertically
0, 0,
$new_width, $new_height,
$width, $height);
imagejpeg($thumb, $output_filename_mid, 85);
答案 0 :(得分:1)
你快到了。您已经发现需要确定旧高度和目标高度之间的比率,以调整要裁剪的边的大小。但是,您需要根据目标比率来确定这一点。
if(($width / $height) > ($thumb_width / $thumb_height)) {
// If image is wider than thumbnail (in aspect ratio sense)
$new_height = $thumb_height;
$new_width = $width / ($height / $thumb_height);
} else {
// If the thumbnail is wider than the image
$new_width = $thumb_width;
$new_height = $height / ($width / $thumb_width);
}
答案 1 :(得分:0)
我实际上正在努力解决这个问题。这是我的代码非常类似于您的代码。你能自己找出差异/问题吗?
我的代码100%工作,完全符合您的需求而且只有这一点。随意使用它!
变量解释:$ imagewidth和$ imageheight自然是输入图像的原始像素大小。 $ crop_ratio_w是裁剪比率宽度,$ crop_ratio_h是裁剪比率高度。
因此,对于我的代码与您的代码:$ crop_ratio_w = $ thumb_width和$ crop_ratio_h = $ thumb_height
//do this if we can start cropping by width (there's enough space on height)
if (($imagewidth * $crop_ratio_h / $crop_ratio_w) < $imageheight){
//count new res
$new_width = $imagewidth;
$new_height = ($imagewidth * $crop_ratio_h / $crop_ratio_w);
//count the height difference, so that new image is cropped in HEIGHT center
$difference = ($imageheight - $new_height);
$y_offset = ($difference / 2);
//create new empty image
$croppedImage = imagecreatetruecolor($new_width, $new_height);
//copy wanted area to the new empty image
imagecopy($croppedImage, $originalImage, 0, 0, 0, $y_offset, $new_width, $new_height);
}
//else on previous condition -- do this if we have to start cropping by height (there's not enough space on height)
else{
//count new res
$new_width = ($imageheight * $crop_ratio_w / $crop_ratio_h);
$new_height = $imageheight;
//count the height difference, so that new image is cropped in WIDTH center
$difference = ($imagewidth - $new_width);
$x_offset = ($difference / 2);
//create new empty image
$croppedImage = imagecreatetruecolor($new_width, $new_height);
//copy wanted area to the new empty image
imagecopy($croppedImage, $originalImage, 0, 0, $x_offset, 0, $new_width, $new_height);
}