圖片裁切是頭像上傳、封面編輯等功能的核心需求。jQuery Jcrop 是一款輕量、強大的前端裁切插件,配合 PHP GD 函數即可完成完整的「選區→裁切→儲存」流程。
<!DOCTYPE html>
<html>
<head>
<title>Jcrop 圖片裁切示例</title>
<script src="jquery-1.6.2.min.js"></script>
<script src="jquery.Jcrop.min.js"></script>
<link rel="stylesheet" href="jquery.Jcrop.min.css" type="text/css" />
<style>
#preview { width: 100px; height: 100px; border: 1px solid #000; overflow: hidden; }
</style>
<script>
$(function() {
$('#imghead').Jcrop({
aspectRatio: 1, // 固定 1:1 比例
onSelect: updateCoords,
onChange: updateCoords
});
});
function updateCoords(c) {
$('#x').val(c.x);
$('#y').val(c.y);
$('#w').val(c.w);
$('#h').val(c.h);
}
function checkCoords() {
if (parseInt($('#w').val()) > 0) return true;
alert('請選擇裁切區域');
return false;
}
</script>
</head>
<body>
<img id="imghead" src="image/b4.jpg" alt="待裁切圖片" />
<form action="crop.php" method="post" onsubmit="return checkCoords();">
<input type="hidden" name="x" id="x" />
<input type="hidden" name="y" id="y" />
<input type="hidden" name="w" id="w" />
<input type="hidden" name="h" id="h" />
<input type="submit" value="確認裁切" />
</form>
</body>
</html>
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$targ_w = $targ_h = 150; // 輸出尺寸 150x150
$jpeg_quality = 90;
$src = 'image/b4.jpg'; // 原圖路徑
$img_r = imagecreatefromjpeg($src);
$dst_r = imagecreatetruecolor($targ_w, $targ_h);
// 核心裁切:重採樣複製選區到目標畫布
imagecopyresampled($dst_r, $img_r, 0, 0,
$_POST['x'], $_POST['y'],
$targ_w, $targ_h,
$_POST['w'], $_POST['h']
);
header('Content-Type: image/jpeg');
imagejpeg($dst_r, null, $jpeg_quality);
imagedestroy($dst_r);
imagedestroy($img_r);
exit;
}
?>
| 技術點 | 說明 |
|---|---|
| aspectRatio: 1 | 強制選區為正方形,適合頭像裁切 |
| onChange / onSelect | 即時同步選區座標到隱藏欄位 |
| imagecopyresampled() | 高品質重採樣縮放,避免鋸齒 |
| imagecreatetruecolor() | 建立真彩色畫布,支援 24-bit 色彩 |
getimagesize() 判斷 MIME,呼叫對應的 imagecreatefromjpeg/png/gif/webp()imagejpeg($dst_r, 'uploads/avatar_'.$uid.'.jpg') 儲存,並回傳 JSON 路徑給前端FileReader API 實現上傳前即時預覽與裁切Jcrop + PHP GD 是經典且穩定的裁切方案,現代專案亦可考慮 Cropper.js 等更新的替代方案。