(此教程包括前端實現圖片裁剪,后端進行獲取裁剪區並保存)
最近有一個需求,微信公眾號上傳圖片,支持自定義裁剪。
以前用過一款裁剪插件cropper,很久沒用了,不知道對移動端操作兼容如何,重新從網上搜索更合適的插件
首先試過PhotoClip,這個插件裁剪區域是固定的,不能自定義縮放(也許需求太匆忙沒有研究透,亦或者可以修改原文件優化這一點),對於用戶體驗不夠好,故,放棄
然后又遇到一款插件---Jcrop,完美符合需求,項目結合百度插件 WebUploader上傳獲取原圖,可適配移動端選取相冊/拍照上傳,獲取到選擇的照片設置給Jcrop(jcrop.setImage(response.url);)進行裁剪
Jcrop優勢:
- 對所有圖片均unobtrusively(無侵入的,保持DOM簡潔)
- 支持寬高比例鎖定
- 支持 minSize/maxSize設置
- 支持改變選區或移 動選區時的回調(Callback)
- 支持用鍵盤微調選區
- 通過API創建互動,比如動畫效果
- 支持CSS樣式
- 簡單便捷,js和css通俗易懂,便於維護
Jcrop實現非常簡答, 有興趣繼續看下文:
1、引用js文件和css文件:
<script type="text/javascript" src="@(WeixinConfig.ResourceAddress)js/jcrop/jquery.Jcrop.js"></script>
<script type="text/javascript" src="@(WeixinConfig.ResourceAddress)js/jcrop/jquery.color.js"></script>
<link rel="stylesheet" href="@(WeixinConfig.ResourceAddress)js/jcrop/jquery.Jcrop.css">
2、定義裁剪DOM,僅需要一個Img標簽
<div id="jcropBox" style="width: 100%; height: 90%;">
<!-- This is the image we're attaching Jcrop to -->
<img src="" id="jcropTarget" alt="" />
</div>
3、初始化Jcrop
// 默認參數初始化Jcrop $("#jcropTarget").Jcrop();
僅需上面三個步驟,就能完成一個支持移動、縮放、拖放的圖片裁剪
也可以自定義初始化Jcrop的展現形式
$('#jcropTarget').Jcrop({
onChange: showCoords,
onSelect: showCoords,
onRelease: clearCoords,
boxWidth: jcropW,
boxHeight: jcropH,
handleSize: isMobile() === 0 ? 28 : 15
}, function () {
jcrop = this;
jcrop.setSelect([130, 65, 130 + 350, 65 + 285]);
jcrop.setOptions({
bgFade: true,
bgOpacity: 0.5,
bgColor: 'black',
addClass: 'jcrop-light',
handleOffset: 20
});
});
文章最后有各參數說明表格,此處不做一一解釋
function showCoords(c) { x = c.x; y = c.y; w = c.w; h = c.h; }; function clearCoords() { $('#coords input').val(''); };
進一步對圖片進行保存,我采取的是獲取裁剪圖片的x,y,width,height
添加一個裁剪按鈕
<button id="btnSaveJcropImg" class="btnJcrop">裁剪</button>
注冊click事件,把最終裁剪的x,y,w,h參數傳給后端,進行分析保存
/// <summary> /// 保存裁剪后的新圖片(通過x,y,w,h對原圖進行截取) /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <param name="w"></param> /// <param name="h"></param> /// <param name="fileName">文件名,WebUploader上傳到服務器的原圖</param> /// <returns></returns> [HttpPost] public JsonResult JcropUploadProcess(int x, int y, int w, int h, string fileName) { try { ViewBag.YearEndUploadUrl = yearEndUploadUrl; //保存到臨時文件夾 string path = "/upload/yearend/"; string localPath = HttpContext.Server.MapPath(path); if (!System.IO.Directory.Exists(localPath)) { System.IO.Directory.CreateDirectory(localPath); } localPath = HttpContext.Server.MapPath(path + "/temp"); if (!System.IO.Directory.Exists(localPath)) { System.IO.Directory.CreateDirectory(localPath); } // 圖片路徑 string oldPath = System.IO.Path.Combine(localPath, fileName); // 新圖片路徑 string newPath = System.IO.Path.GetExtension(oldPath); newPath = oldPath.Substring(0, oldPath.Length - newPath.Length) + "_new" + newPath; //定義截取矩形 System.Drawing.Rectangle cropArea = new System.Drawing.Rectangle(x, y, w, h); //要截取的區域大小 //加載圖片 System.Drawing.Image img = System.Drawing.Image.FromStream(new System.IO.MemoryStream(System.IO.File.ReadAllBytes(oldPath))); //定義Bitmap對象 System.Drawing.Bitmap bmpImage = new System.Drawing.Bitmap(img); //進行裁剪 System.Drawing.Bitmap bmpCrop = bmpImage.Clone(cropArea, bmpImage.PixelFormat); //保存成新文件 bmpCrop.Save(newPath); //釋放對象 img.Dispose(); bmpCrop.Dispose(); //獲取文件名+后綴 string filePathName = System.IO.Path.GetFileName(newPath); return Json(new { ret = 0, jsonrpc = "2.0", id = "id", filePath = filePathName, url = yearEndUploadUrl + "temp/" + filePathName }); } catch (Exception ex) { return Json(new { ret = 1, jsonrpc = 2.0, error = new { code = 102, message = ex.Message }, id = "id" }); } }
最后附上擴展說明
Options參數說明
| 參數名 | 默認值 | 參數說明 |
| allowSelect | true | 允許新選框 |
| allowMove | true | 允許選框移動 |
| allowResize | true | 允許選框縮放 |
| trackDocument | true | |
| baseClass | "jcrop" | 基礎樣式名前綴。說明:class="jcrop-holder",更改的只是其中的 jcrop。 |
| addClass | null | 添加樣式。假設class名為 "test",則添加樣式后為class="test jcrop-holder" |
| bgColor | "black" | 背景顏色。顏色關鍵字、HEX、RGB 均可。 |
| bgOpacity | 0.6 | 背景透明度 |
| bgFade | false | 是否使用背景過渡效果 |
| borderOpacity | 0.4 | 選框邊框透明度 |
| handleOpacity | 0.5 | 縮放按鈕透明度 |
| handleSize | 9 | 縮放按鈕大小 |
| handleOffset | 5 | 縮放按鈕與邊框的距離 |
| aspectRatio | 0 | 選框寬高比。說明:width/height |
| keySupport | true | 支持鍵盤控制。按鍵列表:上下左右(移動)、Esc(取消)、Tab(跳出裁剪框,到下一個) |
| cornerHandles | true | 允許邊角縮放 |
| sideHandles | true | 允許四邊縮放 |
| drawBorders | true | 繪制邊框 |
| dragEdges | true | 允許拖動邊框 |
| fixedSupport | true | |
| touchSupport | null | |
| boxWidth | 0 | 畫布寬度 |
| boxHeight | 0 | 畫布高度 |
| boundary | 2 | 邊界。說明:可以從邊界開始拖動鼠標選擇裁剪區域 |
| fadeTime | 400 | 過度效果的時間 |
| animationDelay | 20 | 動畫延遲 |
| swingSpeed | 3 | 過渡速度 |
| minSelect | [0,0] | 選框最小選擇尺寸。說明:若選框小於該尺寸,則自動取消選擇 |
| maxSize | [0,0] | 選框最大尺寸 |
| minSize | [0,0] | 選框最小尺寸 |
| onChange | function(){} | 選框改變時的事件 |
| onSelect | function(){} | 選框選定時的事件 |
| onRelease | function(){} | 取消選框時的事件 |
API方法說明
| 方法 | 方法的使用說明 |
| setImage(string) | 設定(或改變)圖像。例:jcrop_api.setImage("newpic.jpg") |
| setOptions(object) | 設定(或改變)參數,格式與初始化設置參數一樣 |
| setSelect(array) | 創建選框,參數格式為:[x,y,x2,y2] |
| animateTo(array) | 用動畫效果創建選框,參數格式為:[x,y,x2,y2] |
| release() | 取消選框 |
| disable() | 禁用 Jcrop。說明:已有選框不會被清除。 |
| enable() | 啟用 Jcrop |
| destroy() | 移除 Jcrop |
| tellSelect() | 獲取選框的值(實際尺寸)。例子:console.log(jcrop_api.tellSelect()) |
| tellScaled() | 獲取選框的值(界面尺寸)。例子:console.log(jcrop_api.tellScaled()) |
| getBounds() | 獲取圖片實際尺寸,格式為:[w,h] |
| getWidgetSize() | 獲取圖片顯示尺寸,格式為:[w,h] |
| getScaleFactor() | 獲取圖片縮放的比例,格式為:[w,h] |
jQuery Jcrop插件下載(其中css文件有部分優化)
