SpringMVC結合Jcrop實現頭像上傳功能!頭像上傳以及之前預覽再以及剪裁
項目中有上傳頭像功能,需要對上傳的圖片進行截取,原來使用的是Flash插件上傳,但是不可控制。最后看到這個Jcrop組件還不錯,就嘗試用了一下感覺還不錯的!這里分享給大家
先說明下我搭建的環境是:springMVC+spring+mybatis。下面直接上代碼:
一、jsp頁面:
<form name="form" action="<%=request.getContextPath()%>/UploadDemo/uploadHeadImage" class="form-horizontal" method="post" enctype="multipart/form-data"> <div class="modal-body text-center"> <div class="zxx_main_con"> <div class="zxx_test_list"> <input class="photo-file" type="file" name="imgFile" id="fcupload" onchange="readURL(this);"/> <img alt="" src="" id="cutimg"/> <input type="hidden" id="x" name="x"/> <input type="hidden" id="y" name="y"/> <input type="hidden" id="w" name="w"/> <input type="hidden" id="h" name="h"/> </div> </div> </div> <div class="modal-footer"> <button id="submit" onclick="">上傳</button> </div> </form>
二、jcrop組件引用情況:
<link rel="stylesheet" href="<c:url value="/resources/uploadPlugin/css/jquery.Jcrop.css"/>" type="text/css"></link> <script type="text/javascript" src="<c:url value="/resources/uploadPlugin/scripts/jquery-1.8.3.js"/>"></script> <script type="text/javascript" src="<c:url value="/resources/uploadPlugin/scripts/jquery.Jcrop.js"/>"></script>
三、jcrop使用方法:(有兩種,先說我使用的,最后在介紹兩種方法的不同之處)
<script type="text/javascript">
//定義一個全局api,這樣操作起來比較靈活
var api = null;
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.readAsDataURL(input.files[0]);
reader.onload = function (e) {
$('#cutimg').removeAttr('src');
$('#cutimg').attr('src', e.target.result);
api = $.Jcrop('#cutimg', {
setSelect: [ 20, 20, 200, 200 ],
aspectRatio: 1,
onSelect: updateCoords
});
};
if (api != undefined) {
api.destroy();
}
}
function updateCoords(obj) {
$("#x").val(obj.x);
$("#y").val(obj.y);
$("#w").val(obj.w);
$("#h").val(obj.h);
};
}
</script> 四、后臺代碼:
@RequestMapping(value = "/uploadHeadImage")
public String uploadHeadImage(
HttpServletRequest request,
@RequestParam(value = "x") String x,
@RequestParam(value = "y") String y,
@RequestParam(value = "h") String h,
@RequestParam(value = "w") String w,
@RequestParam(value = "imgFile") MultipartFile imageFile
) throws Exception{
System.out.println("==========Start=============");
String realPath = request.getSession().getServletContext().getRealPath("/");
String resourcePath = "resources/uploadImages/";
if(imageFile!=null){
if(FileUploadUtil.allowUpload(imageFile.getContentType())){
String fileName = FileUploadUtil.rename(imageFile.getOriginalFilename());
int end = fileName.lastIndexOf(".");
String saveName = fileName.substring(0,end);
File dir = new File(realPath + resourcePath);
if(!dir.exists()){
dir.mkdirs();
}
File file = new File(dir,saveName+"_src.jpg");
imageFile.transferTo(file);
String srcImagePath = realPath + resourcePath + saveName;
int imageX = Integer.parseInt(x);
int imageY = Integer.parseInt(y);
int imageH = Integer.parseInt(h);
int imageW = Integer.parseInt(w);
//這里開始截取操作
System.out.println("==========imageCutStart=============");
ImageCut.imgCut(srcImagePath,imageX,imageY,imageW,imageH);
System.out.println("==========imageCutEnd=============");
}
}
return "user/uploadImg/test";
} 五、ImageCut.java工具類:
/**
* 截取圖片
* @param srcImageFile 原圖片地址
* @param x 截取時的x坐標
* @param y 截取時的y坐標
* @param desWidth 截取的寬度
* @param desHeight 截取的高度
*/
public static void imgCut(String srcImageFile, int x, int y, int desWidth,
int desHeight) {
try {
Image img;
ImageFilter cropFilter;
BufferedImage bi = ImageIO.read(new File(srcImageFile+"_src.jpg"));
int srcWidth = bi.getWidth();
int srcHeight = bi.getHeight();
if (srcWidth >= desWidth && srcHeight >= desHeight) {
Image image = bi.getScaledInstance(srcWidth, srcHeight,Image.SCALE_DEFAULT);
cropFilter = new CropImageFilter(x, y, desWidth, desHeight);
img = Toolkit.getDefaultToolkit().createImage(
new FilteredImageSource(image.getSource(), cropFilter));
BufferedImage tag = new BufferedImage(desWidth, desHeight,
BufferedImage.TYPE_INT_RGB);
Graphics g = tag.getGraphics();
g.drawImage(img, 0, 0, null);
g.dispose();
//輸出文件
ImageIO.write(tag, "JPEG", new File(srcImageFile+"_cut.jpg"));
}
} catch (Exception e) {
e.printStackTrace();
}
} 六、jcrop的兩種使用方式:
1、jQuery('#cropbox').Jcrop({
onChange: showCoords,
onSelect: showCoords
});
2、var api = $.Jcrop('#cropbox',{
onChange: showPreview,
onSelect: showPreview,
aspectRatio: 1
});
這里推薦大家使用第二種方式,將Jcrop生成的對象賦給一個全局變量,這樣操作起來更靈活,如調用api.destroy();方法可以銷毀 Jcorp,這樣我們在實際使用中會更靈活一些,因為直接改變要裁剪圖片的路徑會導致Jcorp的出錯,如果想要變更編輯的圖片我們需要銷毀Jcorp, 變更圖片的屬性后再次為圖片附加Jcorp。
參看:1、 jQuery Jcrop 圖像裁剪 2、Jcrop的官網
來自:http://my.oschina.net/zhengweishan/blog/368402 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!