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

Jcrop 圖片裁剪插件完整接入指南:從基礎到 API 進階

     編輯:Java 程式設計入門

Jcrop 核心能力

  • 任意比例選區、固定比例(頭像常用 1:1)
  • 實時預覽面板、動畫過渡、背景遮罩自定義
  • 事件回調:onChange、onSelect、onRelease
  • API 控制:setSelect、animateTo、release、disable/enable、setImage

項目結構與引入

webapp/
├── css/
│   ├── jquery.Jcrop.css
│   └── jquery.Jcrop.extras.css
├── js/
│   ├── jquery.min.js
│   ├── jquery.Jcrop.js
│   └── jquery.color.js (動畫顏色漸變需引入)
└── demo_files/ (示例圖片)

頁面引入順序:jQuery → Jcrop JS → Jcrop CSS → extras CSS (可選)

五大教程級示例

1. Hello World —— 最小配置

$('#target').Jcrop();

默認行為:自由拖拽選區,無回調,無預覽。

2. 事件處理器 —— 實時同步坐標到表單

$('#target').Jcrop({
    onChange: updateCoords,
    onSelect: updateCoords,
    onRelease: clearCoords
});

function updateCoords(c) {
    $('#x1').val(c.x); $('#y1').val(c.y);
    $('#x2').val(c.x2); $('#y2').val(c.y2);
    $('#w').val(c.w); $('#h').val(c.h);
}
function clearCoords() { $('input', '#coords').val(''); }

典型用於頭像上傳前端預填裁剪參數。

3. 固定比例 + 預覽面板

var api, boundx, boundy;
$('#target').Jcrop({
    onChange: updatePreview,
    onSelect: updatePreview,
    aspectRatio: 1 // 1:1
}, function() {
    api = this;
    var bounds = this.getBounds();
    boundx = bounds[0]; boundy = bounds[1];
});

function updatePreview(c) {
    if (c.w > 0) {
        var rx = 100 / c.w, ry = 100 / c.h;
        $('#preview').css({
            width: Math.round(rx * boundx) + 'px',
            height: Math.round(ry * boundy) + 'px',
            marginLeft: '-' + Math.round(rx * c.x) + 'px',
            marginTop: '-' + Math.round(ry * c.y) + 'px'
        });
    }
}

預覽原理:同一張圖疊加,通過 margin 負值定位顯示選區內容。

4. 動畫/過渡效果

$('#target').Jcrop({
    bgFade: true, bgOpacity: 0.3,
    setSelect: [60, 70, 540, 330]
}, function() { api = this; });

// 程序化動畫
$('#anim1').click(() => api.animateTo([217, 122, 382, 284]));
$('#anim2').click(() => api.animateTo([20, 20, 580, 380]));

需引入 jquery.color.js 支持背景顏色漸變。

5. 完整 API 演示面板

  • 動態啟用/禁用、銷毀/重掛
  • 運行時切換圖片(setImage)
  • 動態調整 aspectRatio、minSize/maxSize
  • 選區操作鎖定:allowSelect、allowMove、allowResize

後端配合:坐標轉存與圖片處理

前端提交 x,y,x2,y2,w,h,後端(Java 示例):

BufferedImage src = ImageIO.read(new File(uploadPath));
BufferedImage cropped = src.getSubimage(x, y, w, h);
ImageIO.write(cropped, "jpg", new File(outputPath));

注意:前端圖片若經過 CSS 縮放顯示,**必須按原圖比例換算坐標**,或直接使用 Jcrop 返回的原圖坐標(getBounds() 輔助)。

避坑清單

  • jQuery 版本兼容:Jcrop 0.9.x 需 jQuery 1.7+,不支持 jQuery 3.x 精簡版
  • 圖片跨域:需同域或配置 CORS,否則無法讀取像素數據
  • 動態添加的圖片:需 onload 後再初始化 Jcrop
  • 銷毀後重建:調用 api.destroy() 再重新 $('#target').Jcrop()

Jcrop 雖已停止維護,但 API 成熟穩定,配合少量代碼即可構建專業級裁剪體驗。

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