用戶上傳頭像常需從大圖裁剪指定區域。imagecopyresampled() 支持重採樣,裁剪同時可縮放,質量優於 imagecopyresized()。本文演示固定輸出尺寸的裁剪函數。
function cropImage($filename, $srcX, $srcY, $dstW, $dstH) {
// 1. 創建目標畫布(輸出尺寸)
$dst = imagecreatetruecolor($dstW, $dstH);
// 2. 載入源圖
$src = imagecreatefromjpeg($filename); // 假設 JPEG
// 3. 裁剪+重採樣
// imagecopyresampled(dst, src, dst_x, dst_y, src_x, src_y, dst_w, dst_h, src_w, src_h)
// 此處 src_w/src_h 同 dst_w/dstH,實現 1:1 裁剪無縮放
imagecopyresampled($dst, $src, 0, 0, $srcX, $srcY, $dstW, $dstH, $dstW, $dstH);
// 4. 保存(可加前綴避免覆蓋原圖)
imagejpeg($dst, $filename);
imagedestroy($dst);
imagedestroy($src);
}
// 從 (50,50) 起裁剪 200x200 區域
cropImage("brophp.jpg", 50, 50, 200, 200);
| 參數 | 含義 |
|---|---|
$srcX, $srcY | 源圖裁剪區域左上角座標 |
$dstW, $dstH | 目標圖寬高(輸出尺寸) |
src_w, src_h | 源圖裁剪區域寬高(若與目標不同則觸發縮放) |
function smartCrop($file, $x, $y, $w, $h, $output = null) {
$info = getimagesize($file);
$mime = $info['mime'];
$type = $info[2];
$create = 'imagecreatefrom' . image_type_to_extension($type, false);
$outputFunc = 'image' . image_type_to_extension($type, false);
$src = $create($file);
$dst = imagecreatetruecolor($w, $h);
imagecopyresampled($dst, $src, 0, 0, $x, $y, $w, $h, $w, $h);
$outFile = $output ?: $file;
header("Content-Type: $mime");
$outputFunc($dst, $outFile);
imagedestroy($src);
imagedestroy($dst);
}
掌握 imagecopyresampled 九參數映射關係,可實現裁剪、縮放、縮略圖生成等所有幾何變換需求。