jQuery插件imgAreaSelect

1、需求包:

jquery.imgareaselect.js

jquery.imgareaselect.pack.js

jquery-1.6.1.min.js

ajaxfileupload-min.js

json-lib-2.3-jdk15.jar

commons-fileupload-1.2.2.jar


2、前端页面

[html]  view plain  copy
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  2. <html xmlns="http://www.w3.org/1999/xhtml">  
  3. <head>  
  4. <title></title>  
  5. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
  6. <link href="css/imgareaselect-default.css" rel="stylesheet" type="text/css" />  
  7. <script type="text/javascript" src="js/jquery-1.6.1.min.js"></script>  
  8. <script type="text/javascript" src="js/ajaxfileupload-min.js"></script>  
  9. <script type="text/javascript" src="js/jquery.imgareaselect.min.js"></script>  
  10. <script type="text/javascript" src="js/jquery.imgareaselect.pack.js"></script>  
  11. <script type="text/javascript" src="js/upload.js"></script>  
  12. </head>  
  13. <body>  
  14.     <input type="hidden" name="x1" value="0" />  
  15.     <input type="hidden" name="y1" value="0" />  
  16.     <input type="hidden" name="x2" value="100" />  
  17.     <input type="hidden" name="y2" value="100" />   
  18.     <input id="fileToUpload" name="fileToUpload" type="file" onchange="uploadImage();"/>  
  19.     <div id="facediv" style="display:none;z-index:100;">  
  20.         <img id="face" />  
  21.     </div>  
  22. </body>  
  23. </html>  

[javascript]  view plain  copy
  1. function uploadImage() {  
  2.     $.ajaxFileUpload( {  
  3.         url : 'photo',// 需要链接到服务器地址  
  4.         fileElementId : 'fileToUpload',// 文件选择框的id属性  
  5.         dataType : 'json',// 服务器返回的格式,可以是json  
  6.         data : {"operation":1},  
  7.         success : function(data) {  
  8.             if (data['result'] == 1) {  
  9.                 $("#facediv").css({"display":"block"});  
  10.                 $("#face").attr("src",data['path']);  
  11.                   
  12.                 $('<div><img src="' + data['path'] + '" style="position: relative;" /><div>')  
  13.                     .css({  
  14.                         float'left',  
  15.                         position: 'relative',  
  16.                         overflow: 'hidden',  
  17.                         width: '100px',  
  18.                         height: '100px'  
  19.                     }).insertAfter($('#face'));  
  20.                   
  21.                 $('<button id="btnSubmit">提交</button>')  
  22.                 .click(function (){  
  23.                     cutImage(data['path']);  
  24.                 }).insertAfter($('#facediv'));  
  25.                   
  26.                 $('#face').imgAreaSelect({  
  27.                     maxWidth: 100, maxHeight: 100,  
  28.                     minWidth: 63, minHeight:63,  
  29.                     x1:0,y1:0,x2:100,y2:100,  
  30.                     aspectRatio: '1:1',   
  31.                     onSelectChange: function (img, selection) {  
  32.                         var scaleX = 100 / (selection.width || 1);  
  33.                         var scaleY = 100 / (selection.height || 1);  
  34.                         
  35.                         $('#face + div > img').css({  
  36.                             width: Math.round(scaleX * 400) + 'px',  
  37.                             height: Math.round(scaleY * 300) + 'px',  
  38.                             marginLeft: '-' + Math.round(scaleX * selection.x1) + 'px',  
  39.                             marginTop: '-' + Math.round(scaleY * selection.y1) + 'px'  
  40.                         });  
  41.                     },  
  42.                     onSelectEnd: function (img, selection) {  
  43.                         $('input[name="x1"]').val(selection.x1);  
  44.                         $('input[name="y1"]').val(selection.y1);  
  45.                         $('input[name="x2"]').val(selection.x2);  
  46.                         $('input[name="y2"]').val(selection.y2);  
  47.                     }   
  48.                 });  
  49.             }  
  50.         },  
  51.         error : function(data) {  
  52.         }  
  53.     });  
  54. }  
  55.   
  56. function cutImage(path) {  
  57.     $.ajax( {  
  58.         type : "POST",  
  59.         url:"photo",  
  60.         dateType:"json",  
  61.         data:{"operation":2,"x1":$('input[name="x1"]').val(),  
  62.         "x2":$('input[name="x2"]').val(),  
  63.         "y1":$('input[name="y1"]').val(),  
  64.         "y2":$('input[name="y2"]').val(),  
  65.         "path":path},  
  66.         success : function(data) {  
  67.             top.location.href="photo_view.vm?path="+data["path"];  
  68.         },  
  69.         error:function(data) {  
  70.               
  71.         }  
  72.     });  
  73. }  

3、后台处理:

[java]  view plain  copy
  1. public class PhotoServlet extends HttpServlet {  
  2.   
  3.     private static final long serialVersionUID = 5653610348191435218L;  
  4.   
  5.     @Override  
  6.     protected void doPost(HttpServletRequest request, HttpServletResponse resp)  
  7.             throws ServletException, IOException {  
  8.           
  9.         String requestType = request.getContentType();  
  10.         if (requestType != null && requestType.indexOf("multipart/form-data") != -1) {  
  11.             FileItemFactory factory = new DiskFileItemFactory();  
  12.             ServletFileUpload upload = new ServletFileUpload(factory);  
  13.             List items;  
  14.             try {  
  15.                 items = upload.parseRequest(request);  
  16.                 Iterator iter = items.iterator();  
  17.                 String webRoot = request.getSession().getServletContext()  
  18.                 .getRealPath("/");  
  19.                 while (iter.hasNext()) {  
  20.                     FileItem item = (FileItem) iter.next();  
  21.                     if (!item.isFormField()) {  
  22.                         String suffix = item.getName().substring(item.getName().lastIndexOf("."));  
  23.                         String name = String.valueOf(System.currentTimeMillis());  
  24.                         StringBuffer sourcePath = new StringBuffer();  
  25.                         sourcePath.append(webRoot);  
  26.                         sourcePath.append(File.separator);  
  27.                         sourcePath.append("tmp");  
  28.                         sourcePath.append(File.separator);  
  29.                         sourcePath.append(name);  
  30.                         sourcePath.append("_source");  
  31.                         sourcePath.append(suffix);  
  32.                           
  33.                         File imageFile= new File(sourcePath.toString());  
  34.                         if (!imageFile.getParentFile().exists()) {  
  35.                             imageFile.getParentFile().mkdirs();  
  36.                         }  
  37.                         item.write(imageFile);            
  38.                           
  39.                         JSONObject result = new JSONObject();  
  40.                         result.put("result"1);  
  41.                         result.put("path""http://localhost:8080/testxml/tmp/" + imageFile.getName());  
  42.                           
  43.                         this.responseJSON(resp, result.toString());  
  44.                         break;  
  45.                     }  
  46.                 }  
  47.             } catch (FileUploadException e) {  
  48.                 // TODO Auto-generated catch block  
  49.                 e.printStackTrace();  
  50.             } catch (Exception e) {  
  51.                 // TODO Auto-generated catch block  
  52.                 e.printStackTrace();  
  53.             }  
  54.         } else {  
  55.             Integer x1 = Integer.parseInt(request.getParameter("x1"));  
  56.             Integer y1 = Integer.parseInt(request.getParameter("y1"));  
  57.             Integer x2 = Integer.parseInt(request.getParameter("x2"));  
  58.             Integer y2 = Integer.parseInt(request.getParameter("y2"));  
  59.             String path = request.getParameter("path");  
  60.             String fileName = path.substring(path.lastIndexOf("/")+1);  
  61.             String suffix = fileName.substring(fileName.lastIndexOf("."));  
  62.               
  63.             String webRoot = request.getSession().getServletContext().getRealPath("/");  
  64.               
  65.             StringBuffer sourcePath = new StringBuffer();  
  66.             sourcePath.append(webRoot);  
  67.             sourcePath.append(File.separator);  
  68.             sourcePath.append("tmp");  
  69.             sourcePath.append(File.separator);  
  70.             sourcePath.append(fileName);  
  71.               
  72.             StringBuffer targetPath = new StringBuffer();  
  73.             targetPath.append(webRoot);  
  74.             targetPath.append(File.separator);  
  75.             targetPath.append("tmp");  
  76.             targetPath.append(File.separator);  
  77.             targetPath.append(fileName.substring(0, fileName.lastIndexOf("_")));  
  78.             targetPath.append(suffix);  
  79.               
  80.             cutImage(suffix.substring(1), sourcePath.toString(), targetPath.toString(),  
  81.                     x1, y1, x2, y2);  
  82.               
  83.             new File(sourcePath.toString()).delete();  
  84.               
  85.             JSONObject result = new JSONObject();  
  86.             result.put("result"1);  
  87.             result.put("path""http://localhost:8080/testxml/tmp/" + fileName.substring(0, fileName.lastIndexOf("_")) + suffix);  
  88.             resp.setContentType("application/json");  
  89.             this.responseJSON(resp, result.toString());  
  90.         }  
  91.     }  
  92.     protected void responseJSON(HttpServletResponse response, String jsonStr) {  
  93.         response.setCharacterEncoding("utf-8");  
  94.         PrintWriter writer;  
  95.         try {  
  96.             writer = response.getWriter();  
  97.             writer.write(jsonStr);  
  98.             writer.flush();  
  99.         } catch (IOException e) {  
  100.         }  
  101.     }  
  102.     public static void cutImage(String suffix, String sourcePath, String targetPath,  
  103.             int x1, int y1, int x2, int y2) {  
  104.         try {  
  105.             Image img;  
  106.             ImageFilter cropFilter;  
  107.             File sourceImgFile = new File(sourcePath);  
  108.             BufferedImage bi = ImageIO.read(sourceImgFile);  
  109.             int srcWidth = bi.getWidth();  
  110.             int srcHeight = bi.getHeight();  
  111.             int destWidth = x2 - x1;  
  112.             int destHeight = y2 - y1;  
  113.             if (srcWidth >= destWidth && srcHeight >= destHeight) {  
  114.                 Image image = bi.getScaledInstance(srcWidth, srcHeight,  
  115.                         Image.SCALE_DEFAULT);  
  116.                 cropFilter = new CropImageFilter(x1, y1, destWidth, destHeight);  
  117.                 img = Toolkit.getDefaultToolkit().createImage(  
  118.                         new FilteredImageSource(image.getSource(), cropFilter));  
  119.                 BufferedImage tag = new BufferedImage(destWidth, destHeight,  
  120.                         BufferedImage.TYPE_INT_RGB);  
  121.                 Graphics g = tag.getGraphics();  
  122.                 g.drawImage(img, 00null);  
  123.                 g.dispose();  
  124.                 ImageIO.write(tag, suffix, new File(targetPath));                 
  125.             }  
  126.         } catch (Exception e) {  
  127.             e.printStackTrace();  
  128.         }  
  129.     }  
  130.   
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值