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);
您的代碼工作得很好!不過,我認爲......你能告訴我在哪裏編輯?如果寬度超過高度..我不希望裁剪高度。 –