本文記錄頭像裁剪上傳功能的實作過程,用到的技術是 jQuery、Spring MVC,裁剪元件選用 Jcrop。過程中有幾個坑,值得一一記下來。
<script src="js-jcrop/jquery.min.js"></script>
<script src="js-jcrop/jquery.Jcrop.js"></script>
<script src="js/jquery-form.js"></script>
<link rel="stylesheet" href="../css/jquery.Jcrop.css" type="text/css" />
<style type="text/css">
/* 預覽區尺寸 */
#preview-pane .preview-container { width: 110px; height: 110px; overflow: hidden; }
#targetDiv{ width: 400px; height: 400px; background-color:#f7fdff; }
</style>
<dl class="dialogBox D_uploadLogo">
<dt class="dialogHeader"><span class="title">頭像上傳</span></dt>
<dd class="dialogBody">
<dl class="bisinessLogo">
<dt class="title">預覽</dt>
<dd class="img">
<div id="preview-pane">
<div class="preview-container">
<img src="" id="target2" class="jcrop-preview" alt="未選擇圖片" />
</div>
</div>
</dd>
<dd class="tc">尺寸:110*110px</dd>
</dl>
<dl class="bisinessInfo">
<dt class="btnBox02">
<form id="fileUp" action="/file/img/upload" method="post"
enctype="multipart/form-data" target="ifm">
<a class="btnGray" href="javascript:;">
<span class="text" id="format">選擇圖片</span>
<input type="file" id="file_upload" class="inputFile" name="userphoto" />
<input type="hidden" id="w" name="w" />
<input type="hidden" id="h" name="h" />
<input type="hidden" id="x" name="x" />
<input type="hidden" id="y" name="y" />
</a>
</form>
</dt>
<dd class="info">
請從本機選擇一張照片,支援 jpg、png 格式
<span id="msg"></span>
<div id="targetDiv">
<img src="" id="target" width="400" height="400" alt="未選擇圖片" />
</div>
</dd>
</dl>
</dd>
<input type="hidden" id="filePathInput" value="" />
<dd class="dialogBottom">
<a class="btnBlue btn_confirm" href="javascript:;" onclick="photoSummit();">確定</a>
<a class="btnGray btn_cancel" href="javascript:;" onclick="hideDialog();">取消</a>
</dd>
</dl>
裁剪框選到的 w、h、x、y 四個值分別放在隱藏欄位裡,送出時一起帶到後端。
檔案上傳用的是 <input type="file" />。但如果用一般 form 送出,頁面就會跳轉刷新,體驗很差。jQuery 本身在舊版本中不支援檔案上傳,這時可以借助 jquery-form.js:
$("#file_upload").change(function() {
$("#msg").text('');
var oFile = $(this)[0].files[0];
// 檢查檔案大小
if (oFile.size > 1 * 1024 * 1024) {
$("#msg").text('檔案太大,請選擇 1M 以下的圖像').css('color', 'red');
$(this).val("");
return;
}
// 檢查副檔名
var filepath = $(this).val();
var ext = filepath.substring(filepath.lastIndexOf(".")).toUpperCase();
if (ext != ".JPEG" && ext != ".PNG" && ext != ".JPG") {
$("#msg").text('請選擇有效的圖像檔(jpg / png)').css('color', 'red');
$(this).val("");
return;
}
$("#fileUp").ajaxSubmit({
type: "POST",
url: "/file/img/upload",
dataType: "json",
success: function(parameter){
$("#target2").attr('src', '/upload/' + parameter.fileName);
$("#filePathInput").val('/upload/' + parameter.fileName);
if ($("#format").text() == "重新上傳") {
jcrop_api.destroy(); // 重點:先銷毀舊的裁剪物件
}
$("#format").text("重新上傳");
openJcrop('/upload/' + parameter.fileName);
},
error: function(){ alert("ajax 傳輸發生錯誤!"); }
});
});
注意這裡用的是 ajaxSubmit(來自 jquery-form.js),而不是 $.ajax。這個方法會自動處理 FormData,是舊專案中實現「Ajax 上傳檔案」的常見做法。
@Controller
@RequestMapping(value = "/file")
public class FileEditorController {
private Logger logger = LoggerFactory.getLogger(FileEditorController.class);
ImgEditor imgEditor = new ImgEditor();
public String filePathFinal = "";
/** 依裁剪參數剪切並縮放 */
@RequestMapping(value = "/img/cutandscale", method = RequestMethod.POST)
public @ResponseBody int cutAndscaleimg(
@RequestParam("w") int w,
@RequestParam("h") int h,
@RequestParam("x") int x,
@RequestParam("y") int y) {
imgEditor.cut(filePathFinal, filePathFinal, x, y, w, h);
imgEditor.scale(filePathFinal, filePathFinal, 110, 110, false);
return 1;
}
/** 接收上傳並先縮放到 400x400 */
@RequestMapping(value = "/img/upload", method = RequestMethod.POST)
public @ResponseBody Parameters addImage(
@RequestParam("userphoto") MultipartFile file,
HttpServletRequest request, HttpServletResponse response, HttpSession session) {
String filePath = "";
try {
filePath = imgEditor.uploadFile(file, request, session);
filePathFinal = filePath;
imgEditor.zoomImage(filePath, filePath, 400, 400);
} catch (IOException e) {
e.printStackTrace();
}
logger.info("filePath: " + filePath);
Parameters parameter = new Parameters();
parameter.setFileName(imgEditor.getFileName(file, request, session));
return parameter;
}
}
public class ImgEditor {
/** 直接改變尺寸 */
public void zoomImage(String srcFileName, String tagFileName, int width, int height) {
try {
BufferedImage bi = ImageIO.read(new File(srcFileName));
BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(bi, 0, 0, width, height, null);
ImageIO.write(tag, "jpg", new File(tagFileName));
} catch (IOException e) { e.printStackTrace(); }
}
/** 按比例縮放,可選擇是否補白 */
public void scale(String srcImageFile, String result, int height, int width, boolean bb) {
try {
double ratio = 0.0;
File f = new File(srcImageFile);
BufferedImage bi = ImageIO.read(f);
Image itemp = bi.getScaledInstance(width, height, bi.SCALE_SMOOTH);
if ((bi.getHeight() > height) || (bi.getWidth() > width)) {
ratio = (bi.getHeight() > bi.getWidth())
? (double) height / bi.getHeight()
: (double) width / bi.getWidth();
AffineTransformOp op = new AffineTransformOp(
AffineTransform.getScaleInstance(ratio, ratio), null);
itemp = op.filter(bi, null);
}
if (bb) { // 比例不符時補白
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = image.createGraphics();
g.setColor(Color.white);
g.fillRect(0, 0, width, height);
if (width == itemp.getWidth(null)) {
g.drawImage(itemp, 0, (height - itemp.getHeight(null)) / 2,
itemp.getWidth(null), itemp.getHeight(null), Color.white, null);
} else {
g.drawImage(itemp, (width - itemp.getWidth(null)) / 2, 0,
itemp.getWidth(null), itemp.getHeight(null), Color.white, null);
}
g.dispose();
itemp = image;
}
ImageIO.write((BufferedImage) itemp, "JPEG", new File(result));
} catch (IOException e) { e.printStackTrace(); }
}
/** 依座標與尺寸裁切 */
public void cut(String srcImageFile, String result, int x, int y, int width, int height) {
try {
BufferedImage bi = ImageIO.read(new File(srcImageFile));
int srcWidth = bi.getHeight(); // 注意:原範例這裡寬高寫反了
int srcHeight = bi.getWidth();
if (srcWidth > 0 && srcHeight > 0) {
Image image = bi.getScaledInstance(srcWidth, srcHeight, Image.SCALE_DEFAULT);
ImageFilter cropFilter = new CropImageFilter(x, y, width, height);
Image img = Toolkit.getDefaultToolkit().createImage(
new FilteredImageSource(image.getSource(), cropFilter));
BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = tag.getGraphics();
g.drawImage(img, 0, 0, width, height, null);
g.dispose();
ImageIO.write(tag, "JPEG", new File(result));
}
} catch (Exception e) { e.printStackTrace(); }
}
/** 產生檔名 */
public String getFileName(MultipartFile file, HttpServletRequest request, HttpSession session) {
String fileName = file.getOriginalFilename();
String[] parts = fileName.split("\\.");
String suffix = parts[parts.length - 1];
String userName = SecurityContextHolder.getContext().getAuthentication().getName();
return getTime() + userName + "." + suffix;
}
/** 存檔並回傳路徑 */
public String uploadFile(MultipartFile file, HttpServletRequest request, HttpSession session)
throws IOException {
String FILE_PATH = session.getServletContext().getRealPath("/") + "upload";
String fileName = getFileName(file, request, session);
File tempFile = new File(FILE_PATH, fileName);
if (!tempFile.getParentFile().exists()) { tempFile.getParentFile().mkdirs(); }
if (!tempFile.exists()) { tempFile.createNewFile(); }
file.transferTo(tempFile);
return FILE_PATH + "\\" + tempFile.getName();
}
public String getTime() {
return new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
}
}
$(function(){
var jcrop_api; // 必須是全域變數,後續才能 destroy
});
// 啟動裁剪
function openJcrop(imgPath){
var boundx, boundy,
xsize = $('#preview-pane .preview-container').width(),
ysize = $('#preview-pane .preview-container').height();
$('#target').Jcrop({
minSize: [110, 110],
onChange: updatePreview,
onSelect: updatePreview,
aspectRatio: xsize / ysize
}, function(){
var bounds = this.getBounds();
boundx = bounds[0];
boundy = bounds[1];
jcrop_api = this; // 保存 API 參照
});
jcrop_api.setImage(imgPath);
function updatePreview(c) {
if (parseInt(c.w) > 0) {
var rx = xsize / c.w, ry = ysize / c.h;
$('#preview-pane .preview-container img').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'
});
$("#w").val(c.w); $("#h").val(c.h);
$("#x").val(c.x); $("#y").val(c.y);
}
}
}
// 送出裁剪結果
function photoSummit(){
if ($("#w").val() > 0 && $("#h").val() > 0) {
$("#fileUp").ajaxSubmit({
type: "POST",
url: "/file/img/cutandscale",
dataType: "json",
success: function(){
$("#msg").text('上傳頭像成功!').css('color', 'red');
window.parent.back($("#filePathInput").val());
},
error: function(){ alert("ajax 傳輸發生錯誤!"); }
});
} else {
$("#msg").text('請用滑鼠框選裁剪範圍').css('color', 'red');
}
}
1. Jcrop 初始化後 img 的 src 改不動。這是最大的坑。Jcrop 一旦作用在某個 img 上,就會建立自己的編輯物件,之後原 img 的 src 變更不會反映到裁剪畫面上。唯一可靠的解法就是先 jcrop_api.destroy() 銷毀舊物件,再重新初始化——這也是為什麼 jcrop_api 必須宣告為全域變數。
2. cut() 方法裡寬高寫反了。範例中 int srcWidth = bi.getHeight(); 這兩行把寬與高對調。目前因為只是拿來跟 0 比大小,剛好不會出錯,但語意是錯的,應改為 getWidth() 與 getHeight()。
3. 用伺服器實體路徑存用戶上傳檔有風險。把檔案存在 getRealPath("/") + "upload" 底下,除了重新部署時容易遺失,更麻煩的是檔名若未徹底消毒,可能有路徑竄改的問題。建議改用 UUID 產生檔名、存到容器外部的指定目錄,並以資料庫保存對應關係。
4. 裁剪參數一定要在後端驗證。x、y、w、h 是前端傳來的,必須檢查是否為正數、以及 x + w 是否超出影像實際寬高,否則 CropImageFilter 會產生非預期的結果甚至例外。
整體流程走通後,頭像上傳的體驗就完整了:選圖 → 預覽 → 框選 → 即時預覽 → 確認裁剪。若日後要支援更多尺寸(例如同時產生 110×110 與 400×400 兩種),只需在後端多呼叫一次 scale 並回傳多組路徑即可。