[英]PHP resize and crop centered-top image
我正在嘗試調整大小(保持寬高比)並裁切多余的圖像(超出縮略圖限制),但是在裁切x =中心和y =頂部的同時這樣做。
我在這里丟失了一些東西,但是我的最終圖像適合縮略圖區域,而不是填充並裁剪多余的圖像。 希望有人可以幫助我。
到目前為止,這是我的代碼:
$image_width = 725; // not static, just an example
$image_height = 409; // not static, just an example
// image can be wide or portrait
$width = 140;
$height = 160;
$thumbnail = imagecreatetruecolor($width, $height);
$white = imagecolorallocate($thumbnail, 255, 255, 255);
imagefill($thumbnail, 0, 0, $white);
$width_ratio = $image_width/$width;
$height_ratio = $image_height/$height;
if ($width_ratio>$height_ratio) {
$dest_width=$width;
$dest_height=$image_height/$width_ratio;
}
else{
$dest_width=$image_width/$height_ratio;
$dest_height=$height;
}
$int_width = ($width - $dest_width)/2;
$int_height = ($height - $dest_height)/2;
imagecopyresampled($thumbnail, $original_image, $int_width, $int_height, 0, 0, $dest_width, $dest_height, $image_width, $image_height);
謝謝!
您的$image_width
, $image_height
, $width
和$height
是靜態的,這意味着$width_ratio
和$height_ratio
總是相同的(分別為: 5.1785714285714
和2.55625
,因此寬度比始終2.55625
高度比)。
在這種情況下,您的代碼塊如下:
if ($width_ratio>$height_ratio) {
$dest_width=$width;
$dest_height=$image_height/$width_ratio;
}
else{
$dest_width=$image_width/$height_ratio;
$dest_height=$height;
}
將始終運行if
再也不else
-刪除它,只留下:
$dest_width=$image_width/$height_ratio;
$dest_height=$height;
並根據較高的值裁剪圖像-在這種情況下,高度將根據新的高度調整大小,多余的寬度將被切除。
希望這就是您想要的!
編輯:
現在,如果相等地切除邊緣,則執行腳本。 如果要從頂部或左側完全切割它們(取決於比例),則:
完全刪除該部分代碼:
$int_width = ($width - $dest_width)/2;
$int_height = ($height - $dest_height)/2;
更改if
else
之前提到的條件:
if($width_ratio < $height_ratio) {
$dest_width=$width;
$dest_height=$image_height/$width_ratio;
$int_width = ($width - $dest_width)/2;
$int_height = 0;
} else {
$dest_width=$image_width/$height_ratio;
$dest_height=$height;
$int_width = 0;
$int_height = ($height - $dest_height)/2;
}
編輯2
水平總是切成相等,垂直總是從頂部切成-如您所願:
if($width_ratio < $height_ratio) {
$dest_width=$width;
$dest_height=$image_height/$width_ratio;
} else {
$dest_width=$image_width/$height_ratio;
$dest_height=$height;
}
$int_width = ($width - $dest_width)/2;
$int_height = 0;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.