【发布时间】:2017-02-25 02:25:55
【问题描述】:
我希望将图像大小调整为 400 x 300 像素。如果图像的宽度大于 400 像素,我希望先调整其大小,然后再裁剪高度。
图像来自远程网站,因此可以是纵向的,也可以是横向的,但我想要实现的是尽可能减少裁剪量,并尽可能在裁剪前先调整大小。
我正在使用以下代码(老实说,我自己很困惑)。比率和数字不太好。代码来自几个 SO 答案代码。
function makeThumb($imgsrc, $imgtarg, $imgtarg_d) {
$ext = exif_imagetype($imgsrc);
if ($ext == false) {
return;
}
//getting the image dimensions
list($width, $height) = getimagesize($imgsrc);
//saving the image into memory (for manipulation with GD Library)
switch($ext) {
case 1:
$myImage = imagecreatefromgif($imgsrc);
break;
case 2:
$myImage = imagecreatefromjpeg($imgsrc);
break;
case 3:
$myImage = imagecreatefrompng($imgsrc);
break;
}
// calculating the part of the image to use for thumbnail
if ($width > $height) {
$y = 0;
$x = ($width - $height) / 2;
$smallestSide = $height;
if ($width >= 400) {
$thumbSizeWidth = 400;
$thumbSizeHeight = 300;
} else {
$thumbSizeWidth = $width;
$thumbSizeHeight = 300;
}
} else {
$x = 0;
$y = ($height - $width) / 2;
$smallestSide = $width;
if ($height >= 300) {
$thumbSizeHeight = 300;
$thumbSizeWidth = 400;
} else {
$thumbSizeHeight = $height;
$thumbSizeWidth = 400;
}
}
$thumb = imagecreatetruecolor($thumbSizeWidth, $thumbSizeHeight);
/*RESIZE FIRST*/
imagecopyresampled($thumb, $myImage, 0, 0, 0, $y, $thumbSizeWidth, $thumbSizeHeight, $width, $height);
/*CROP*/
imagecopyresampled($thumb, $myImage, 0, 0, $x, $y, $thumbSizeWidth, $thumbSizeHeight, $smallestSide, $smallestSide);
//final output
imagejpeg($thumb, $imgtarg_d . '/' . $imgtarg,80);
imagedestroy($thumb);
}
图像总是从中心裁剪(如预期的那样),但如果图像宽度超过 400 像素,它不会先调整大小。
imagecopyresampled($thumb, $myImage, 0, 0, 0, $y, $thumbSizeWidth, $thumbSizeHeight, $width, $height);
imagecopyresampled($thumb, $myImage, 0, 0, $x, $y, $thumbSizeWidth, $thumbSizeHeight, $smallestSide, $smallestSide);
【问题讨论】: