本文分享一個結合 jQuery 與 PHP 的圖片在線裁剪實作。核心思路是:前端傳入選取區域的坐標參數 x、y、寬 w、高 h,後端再用 GD 庫的 imagecopy() 把該區域複製到新建的空白圖像中完成裁剪。
這裡有一個重要提醒:在創建目標圖像時應使用 imagecreatetruecolor() 建立真彩色畫布,若改用 imagecreate(),裁剪出來的圖片會失真。
<?php
/**
* 圖像處理:根據傳入的坐標參數 x, y, w, h
* 分別為選取的 x 坐標、y 坐標、寬度、高度,
* 透過 imagecopy() 將該區域複製至第一步創建的空白圖像中。
* 注意:創建圖像時要用 imagecreatetruecolor() 真彩色,否則用 imagecreate() 圖片會失真。
*/
// 頁面傳過來的比例
$scale = $_GET['scale'];
// 下面的屬性乘以相應的比例
$x = $_GET['x'] * $scale;
$y = $_GET['y'] * $scale;
$w = $_GET['w'] * $scale;
$h = $_GET['h'] * $scale;
// 源路徑
$src = $_GET['src'];
// 是否繼續?若為 off 則在截圖後刪除源圖片
$again = "off";
if(!empty($_GET['again'])){
$again = $_GET['again'];
}
// 第一步:根據傳來的寬、高創建一幅真彩色圖片,正好填充截取的部分
header("Content-type: image/jpeg");
$target = @imagecreatetruecolor($w, $h) or die("Cannot Initialize new GD image stream");
// 第二步:根據路徑獲取源圖像,創建 image 物件
$source = imagecreatefromjpeg($src);
// 第三步:根據參數選取源圖像的一部分填充到第一步創建的圖像中
imagecopy($target, $source, 0, 0, $x, $y, $w, $h);
// 第四步:保存圖像
// 截取並組織新路徑
$pos_path = strripos($src, "/");
$newPath = substr($src, 0, $pos_path - strlen($src)) . "_new/";
// 截取並組織新名稱
$pos_name = strripos($src, ".");
$newName = substr($src, 0, $pos_name);
$pos_name_ = strripos($newName, "/");
$newName = substr($newName, $pos_name_ - strlen($newName) + 1) . "_";
// 生成不帶後綴的圖片
$file = $newPath . $newName;
// 附加 ascii 碼重命名文件,避免重名
for($i=0; $i<26; $i++){
if(is_dir($newPath)){
if(is_file($file . chr(97+$i) . ".jpg")){
continue; // 文件存在則繼續循環
}else{
imagejpeg($target, $file . chr(97+$i) . ".jpg", 100);
if($again == "off"){
unlink($src); // 刪除源文件
unset($_SESSION['url']);
}
break;
}
}else{
mkdir($newPath); // 創建目錄
imagejpeg($target, $file . chr(97+$i) . ".jpg", 100);
if($again == "off"){
unlink($src);
unset($_SESSION['url']);
}
break;
}
}
// 跳轉到首頁
Header("Location: index.php");
?>
整體流程可歸納為四步:建立真彩色目標畫布 → 讀取源圖像 → 以 imagecopy() 複製選取區域 → 保存並可選擇是否刪除源圖。其中透過 $scale 還原顯示尺寸與實際尺寸的差異,並以 ASCII 碼後綴避免檔案重名,是實務上很實用的細節處理。
以上就是 jQuery + PHP 實現圖片在線裁剪的完整內容,希望對大家有所幫助。