【代码】JCrop头像剪辑预览+后端实现

头像上传的插件似乎要用到的时候非常少,查了下网上提供的插件,有些还是使用GPL协议的,果断弃之。

最终选用了JCrop来实现(补充下JCrop提供多种编辑方式和样式,使用MIT License)。

MIT License:



头像上传的部分功能,只要是流程是这样:

1. 用户选择图片,上传至服务器后返回图片地址或其他参数返回给用户界面显示(上传的图片大小要做限制,如果图片大小符合要求但px即像素太大,也需要对图片进行一点比例的缩放处理,再返回)

2. 用户修改或者剪辑图片,根据需要剪辑图片大小和位置(可提供预览界面)

3. 保存图片(保存即将图片选取的坐标值传递至服务器,对图片做剪辑,并缩放至你显示给用户头像的大小)

前端效果一(选择图片):



效果一代码:

   1: <form action="<%=request.getContextPath() %>/uploadImg.do"
   2:                                         name="imgForm1" enctype="multipart/form-data" method="POST">
   3:                                         <input type="file" name="imgFile" onchange="submit();" />
   4:                                     </form>

前端效果二(服务器返回后生成图片提供编辑):



前端效果二代码:

   1: <script src="./scripts/jquery.min.js"></script>
   1:  
   2: <script src="./scripts/jquery.Jcrop.js">
   1: </script>
   2: <link rel="stylesheet" href="./css/jquery.Jcrop.css" type="text/css" />
   3: <%
   4: Object imgWO = request.getAttribute("imgWidth");
   5: int imgWidth = 0;
   6: if(null != imgWO) {
   7:     imgWidth = (Integer)imgWO;
   8: }
   9: Object imgHO = request.getAttribute("imgHeight");
  10: int imgHeight= 0;
  11: if(null != imgHO) {
  12:     imgHeight = (Integer)imgHO;
  13: }
  14: %>
  15: <script language="Javascript">
  16:  
  17:             // Remember to invoke within jQuery(window).load(...)
  18:             // If you don't, Jcrop may not initialize properly
  19:             jQuery(window).load(function(){
  20:  
  21:                 jQuery('#cropbox').Jcrop({
  22:                     setSelect: [ 100, 100, 200, 200 ],
  23:                     onChange: showCoords,
  24:                     onSelect: showPreview,
  25:                     aspectRatio: 1
  26:                 });
  27:             });
  28:  
  29:             // Our simple event handler, called from onChange and onSelect
  30:             // event handlers, as per the Jcrop invocation above
  31:             function showPreview(coords)
  32:             {
  33:                 var imgWidth = 300;
  34:                 var imgHeight = 300;
  35:                 var imgW = <%=imgWidth %>;
  36:                 var imgH = <%=imgHeight %>;
  37:                 if(imgW != null && imgW != 0) {
  38:                     imgWidth = imgW;
  39:                 }
  40:                 if(imgH != null && imgH != 0) {
  41:                     imgHeight = imgH;
  42:                 }
  43:             
  44:                 if (parseInt(coords.w) > 0)
  45:                 {
  46:                     var rx = 100 / coords.w;
  47:                     var ry = 100 / coords.h;
  48:  
  49:                     jQuery('#preview').css({
  50:                         width: Math.round(rx * imgWidth) + 'px',
  51:                         height: Math.round(ry * imgHeight) + 'px',
  52:                         marginLeft: '-' + Math.round(rx * coords.x) + 'px',
  53:                         marginTop: '-' + Math.round(ry * coords.y) + 'px'
  54:                     });
  55:                 }
  56:             }
  57:  
  58:             function showCoords(c)
  59:             {
  60:                 $('#x').val(c.x);
  61:                 $('#y').val(c.y);
  62:                 $('#x2').val(c.x2);
  63:                 $('#y2').val(c.y2);
  64:                 $('#w').val(c.w);
  65:                 $('#h').val(c.h);
  66:             };
  67:           
  68:           
  69:         
</script>
   2: <table width="800px">
   3:             <tr>
   4:                 <%
   1:  
   2:                 Object o = request.getAttribute("imgSrc");
   3:                 String imgSrc = "";
   4:                 if(null != o) {
   5:                     imgSrc = (String)o;
   6:                 }
   7:                 
   8:                 Object o1 = request.getAttribute("imgName");
   9:                 String imgName = "";
  10:                 if(null != o1) {
  11:                     imgName = (String)o1;
  12:                 }
  13:                 
%>
   5:                 <td width="400px">
   6:                 <div align="center">
   7:                 <form action="<%=request.getContextPath() %>/uploadImg.do"
   8:                     name="imgForm1" enctype="multipart/form-data" method="POST">
   9:                 <input type="file" name="imgFile" onchange="submit();" /></form>
  10:                 <img src="<%=imgSrc %>" id="cropbox" /></div>
  11:                 </td>
  12:                 <td width="400px">
  13:                 <form action="<%=request.getContextPath() %>/saveImg.do"
  14:                     name="imgForm" method="POST"><input type="hidden"
  15:                     name="imgName" id="imgName" value="<%=imgName %>" /> <label><input
  16:                     type="hidden" size="4" id="x" name="x" /></label> <label><input
  17:                     type="hidden" size="4" id="y" name="y" /></label> <label><input
  18:                     type="hidden" size="4" id="x2" name="x2" /></label> <label><input
  19:                     type="hidden" size="4" id="y2" name="y2" /></label> <label><input
  20:                     type="hidden" size="4" id="w" name="w" /></label> <label><input
  21:                     type="hidden" size="4" id="h" name="h" /></label>
  22:                 <div align="center">
  23:                 <div style="width:100px;height:100px;overflow:hidden;">
  24:                                             <img src="<%=imgSrc %>" id="preview" />
  25:                                         </div><br><br>
  26:                                         <input type="submit" value="保 存" name="submit"/>
  27:                                     </div>
  28:                                     </form> 
  29:                                 </td>
  30:                             </tr>
  31:                         </table>

前端效果三(保存后显示图片):



后端代码(上传图片+保存图片+缩放图片处理),由于使用SpringMVC,所以这里保存的图片的代码非常简单,你也可以使用smartupload或者commonupload等插件来实现或自己重写:

   1: //上传图片,并返回给浏览器
   2: public ModelAndView uploadImg(HttpServletRequest request,
   3:         HttpServletResponse response) throws Exception {
   4:     ModelAndView mv = new ModelAndView("profileImg.jsp");
   5:     String sourcePath = request.getRealPath("") + "/upload/";
   6:     String serverPath = request.getRealPath("") + "/upload/";
   7:     serverPath = serverPath.replace("\\", "/");
   8:  
   9:     MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
  10:     MultipartFile multipartFile = multipartRequest.getFile("imgFile");
  11:     File file = new File(sourcePath + multipartFile.getOriginalFilename());
  12:     multipartFile.transferTo(file);
  13:  
  14:     BufferedImage bi = ImageIO.read(file);
  15:     int w = bi.getWidth();
  16:     int h = bi.getHeight();
  17:     BufferedImage out = bi.getSubimage(0, 0, w, h);
  18:     out = resizeImage(out, BufferedImage.TYPE_INT_RGB, bi.getWidth(), bi.getHeight());
  19:     ImageIO.write(out, "jpg", file);
  20:     String imgSrc = "upload/" + multipartFile.getOriginalFilename();
  21:     mv.addObject("imgSrc", imgSrc);
  22:     mv.addObject("imgWidth", out.getWidth());
  23:     mv.addObject("imgHeight", out.getHeight());
  24:     mv.addObject("imgName", multipartFile.getOriginalFilename());
  25:     return mv;
  26: }
  27:  
  28: // 保存修剪后的头像
  29: public ModelAndView saveImg(HttpServletRequest request,
  30:         HttpServletResponse response) throws Exception {
  31:     ModelAndView mv = new ModelAndView("profileContent.jsp");
  32:     
  33:     String xStr = request.getParameter("x");
  34:     String yStr = request.getParameter("y");
  35:     String wStr = request.getParameter("w");
  36:     String hStr = request.getParameter("h");
  37:     int x = 0;
  38:     int y = 0;
  39:     int w = 300;
  40:     int h = 300;
  41:     if (null != xStr && !"".equals(xStr)) {
  42:         x = Integer.parseInt(xStr);
  43:     }
  44:  
  45:     if (null != yStr && !"".equals(yStr)) {
  46:         y = Integer.parseInt(yStr);
  47:     }
  48:     if (null != wStr && !"".equals(wStr)) {
  49:         w = Integer.parseInt(wStr);
  50:     } else {
  51:         w = 300;
  52:     }
  53:     if (null != hStr && !"".equals(hStr)) {
  54:         h = Integer.parseInt(hStr);
  55:     } else {
  56:         h = 300;
  57:     }
  58:  
  59:     String imgName = request.getParameter("imgName");
  60:       ServletContext context = getServletContext();
  61:       String  path = context.getRealPath("/") ;
  62:     String  path = request.getRealPath("/") ;
  63:     String sourcePath = path + "upload/";
  64:     String serverPath = path + "upload/" + imgName;
  65:     imgName = MD5.crypt(imgName);
  66:     String hashName = sourcePath + imgName + ".jpg";
  67:     BufferedImage bi = ImageIO.read(new File(serverPath));
  68:  
  69:     BufferedImage out = null;
  70:     if (w > 0 && h >0 && bi.getWidth() >= w && bi.getHeight() >= h) {
  71:         out = bi.getSubimage(x, y, w, h);
  72:     } else {
  73:         out = bi.getSubimage(0, 0, bi.getWidth(), bi.getHeight());
  74:     } 
  75:     
  76:     out = resizeImage(out, BufferedImage.TYPE_INT_RGB, 130, 130);
  77:     ImageIO.write(out, "jpg", new File(hashName));
  78:     response.setHeader("Pragma ", "No-cache ");
  79:     response.setHeader("Cache-Control ", "no-cache ");
  80:     response.setDateHeader("Expires ", 0);
  81:     request.getSession().setAttribute("imgSrc", "upload/" + imgName + ".jpg");
  82:  
  83:     return mv;
  84: }
  85:  
  86: //对图片大小进行缩放处理
  87: public BufferedImage resizeImage(BufferedImage originalImage,
  88:         int type, int width, int height) {
  89:     MathUtil mathUtil = new MathUtil();
  90:     Double rate = 0.0;
  91:     if (width < 300 && height < 300) {
  92:         BufferedImage resizedImage = new BufferedImage(width, height, type);
  93:         Graphics2D g = resizedImage.createGraphics();
  94:         g.drawImage(originalImage, 0, 0, width, height, null);
  95:         g.dispose();
  96:         return resizedImage;
  97:     } else {
  98:         rate = mathUtil.divide(new Double(height), new Double(300));
  99:         height = (int) mathUtil.divide(new Double(height), rate);
 100:         width = (int) mathUtil.divide(new Double(width), rate);
 101:     }
 102:     
 103:     BufferedImage resizedImage = new BufferedImage(width, height, type);
 104:     Graphics2D g = resizedImage.createGraphics();
 105:  
 106:     g.drawImage(originalImage, 0, 0, width, height, null);
 107:     g.dispose();
 108:  
 109:     return resizedImage;
 110: }

由于只是初稿,没有做逻辑和这种异常情况的判断,你可以根据你的需要自己增加。到这基本就完成了。

希望对你有帮助. 如有不足,敬请指出!

----EOF----

posted on 2012-04-21 19:22  FengMichael  阅读(401)  评论(0)    收藏  举报

导航