0
之前,我想调整我的图片到400 x 300像素。如果图像比在宽400像素较大,我想先调整其大小,裁剪高度之前。腓IMG调整大小裁剪
的图像来自远程网站,因此它可以是纵向的,可风景,但我想实现的是,以尽量减少裁剪如果可能的量,如果可能的话在修剪前先调整。
我用下面的代码(我是一个很迷惑自己是诚实的)。比例和数字并不完美。代码来自几个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);
您的代码工作得很好!不过,我认为......你能告诉我在哪里编辑?如果宽度超过高度..我不希望裁剪高度。 –