本文示範一組很實用的組合:FileAPI 負責讀取與處理本機檔案,jcrop 負責框選裁剪區域,兩者搭配就能做到完全不經過伺服器的圖片裁剪與預覽。
整個流程可以拆成五個階段:監聽 change 事件 → 取得檔案清單 → 過濾格式與大小 → 縮圖並掛上 jcrop → 依選取範圍產生預覽並上傳。
var el = document.querySelector('input[type="file"]');
seajs.use(['gallery/jcrop/0.9.12/jcrop.css', 'gallery/jcrop/0.9.12/jcrop.js'], function(){
FileAPI.event.on(el, 'change', function (evt) {
var files = FileAPI.getFiles(evt); // 取得檔案清單
// 第一步:先驗證
FileAPI.filterFiles(files, function (file, info) {
if (!/^image/.test(file.type)) {
alert('圖片格式不正確');
return false;
} else if (file.size > 20 * FileAPI.MB) {
alert('圖片必須小於 20M');
return false;
}
return true;
},
// 第二步:處理通過驗證的檔案
function (files, rejected) {
if (!files.length) return;
var file = files[0];
var img0 = FileAPI.Image(file); // 用於顯示與裁剪
var img1 = FileAPI.Image(file); // 用於產生裁剪結果
var ratio = 0;
// 取得原始尺寸,算出縮放比例
FileAPI.getInfo(file, function (err, info) {
if (!err) {
ratio = info.width > info.height
? info.width / 500
: info.height / 500;
}
});
// 縮到最長邊 500px,掛上 jcrop
img0.resize(500, 500, 'max').get(function (err, img) {
$('#img2').empty().append($(img));
$('#img2').children().Jcrop({
aspectRatio: 1,
bgColor: 'rgba(0,0,0,0.4)',
onSelect: function (c) {
// 把顯示用的座標還原成原始圖座標
img1.matrix.sx = c.x * ratio;
img1.matrix.sy = c.y * ratio;
img1.matrix.sw = c.w * ratio;
img1.matrix.sh = c.h * ratio;
img1.matrix.dw = 500;
img1.matrix.dh = 500;
img1.get(function (err, img) {
$('#img3').html($(img)); // 即時預覽裁剪結果
});
}
});
});
// 點擊上傳
$('#btn').on('click', function () {
FileAPI.upload({
url: '/testUpFile/upFile',
files: { images: img1 },
progress: function (evt) { /* 進度條可在此更新 */ },
complete: function (err, xhr) { /* 處理回應 */ }
});
});
});
});
});
<!DOCTYPE html>
<html>
<head>
<title>圖片上傳裁剪預覽</title>
<meta charset="UTF-8">
<script src="./jquery.min.js"></script>
<script src="./jcrop/jquery.Jcrop.min.js"></script>
<link href="./jcrop/jquery.Jcrop.min.css" rel="stylesheet">
<style>
.upload-btn {
width: 130px; height: 25px; overflow: hidden; position: relative;
border: 3px solid #06c; border-radius: 5px; background: #0cf;
}
.upload-btn:hover { background: #09f; }
.upload-btn__txt {
z-index: 1; position: relative; color: #fff; font-size: 18px;
line-height: 24px; text-align: center; text-shadow: 0 1px 1px #000;
}
.upload-btn input {
top: -10px; right: -40px; z-index: 2; position: absolute;
cursor: pointer; opacity: 0; filter: alpha(opacity=0); font-size: 50px;
}
</style>
</head>
<body>
<div>
<!-- js-fileapi-wrapper 這個 class 是 FileAPI 必要的 -->
<div class="js-fileapi-wrapper upload-btn" id="choose">
<input name="files" type="file" multiple />
<button id="btn">上傳</button>
</div>
<div id="images">
<div id="img2"></div> <!-- 原圖 + 裁剪框 -->
<div id="img3"></div> <!-- 裁剪預覽 -->
</div>
</div>
<script>window.FileAPI = { staticPath: './fileapi/' };</script>
<script src="./fileapi/FileAPI.min.js"></script>
</body>
</html>
FileAPI.getInfo 是非同步的,若在回呼之前就觸發 jcrop 的 onSelect,ratio 可能還是 0,導致裁剪座標全錯。較穩妥的做法是把 jcrop 的初始化寫在 getInfo 的回呼裡。