首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 搭配 jQuery Jcrop 實現圖片裁切上傳功能完整教學

     編輯:PHP 綜合知識

圖片裁切是頭像上傳、封面編輯等功能的核心需求。jQuery Jcrop 是一款輕量、強大的前端裁切插件,配合 PHP GD 函數即可完成完整的「選區→裁切→儲存」流程。

前端頁面(HTML + JavaScript)

<!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>

後端處理(crop.php)

<?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()
  • 安全驗證:檢查檔案大小、維度、MIME 類型,防止惡意上傳
  • 儲存檔案而非直接輸出:實際專案中應 imagejpeg($dst_r, 'uploads/avatar_'.$uid.'.jpg') 儲存,並回傳 JSON 路徑給前端
  • 前端預覽:利用 FileReader API 實現上傳前即時預覽與裁切

Jcrop + PHP GD 是經典且穩定的裁切方案,現代專案亦可考慮 Cropper.js 等更新的替代方案。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved