jQuery与Java实现图片的剪切

Java头像剪切上传功能完整实现指南 在现代Web应用中,用户头像作为个性化展示的重要组成部分,其上传与剪切功能已成为标准配置。本章将围绕头像处理流程展开,从用户选择图片、前端预览、图像剪切、上传传输到后端接收与存储,构建完整的功能认知体系。该功能涵盖前端交互设计、图像数据处理、HTTP文件上传协议、Java后端接收与图像操作等多个技术层面,是前后端协作的典型应用场景。通过本章学习,读者将掌握头像处理的整体架构与关键环节,为后续章节的代码实现和优化策略打下坚实基础。 阅读详情
一 参考资料 
1 jquery Jcrop 头像,logo截图  
http://terje.blog.163.com/blog/static/11924371201101311319664/  
2 javascript+java截取图像,图像处理 
http://www.blogjava.net/b47248054/articles/200685.html  
3 js+java 截取照片中的头像 
http://blog.youkuaiyun.com/dsj188/article/details/4313662  
4 java+jsp 截头像图片 
http://ldf2008rw.iteye.com/blog/502793  
5 Java生成缩略图之Thumbnailator 
http://rensanning.iteye.com/blog/1545708  
Thumbnailator 是一个为Java界面更流畅的缩略图生成库。从API提供现有的图像文件和图像对象的缩略图中简化了缩略过程,两三行代码就能够从现有图片生成缩略图,且允许微调缩略图生成,同时保持了需要写入到最低限度的代码量。同时还支持根据一个目录批量生成缩略图。  http://code.google.com/p/thumbnailator/ 这个不错!支持!  

二 解决思路  
1 通过smart-upload文件上传组件将图片上传到服务器,并得到图片文件地址传递到前台的img组件显示 
2 在客户端用JS获取图片X坐标,Y坐标,宽度和高度这四个参数并设置到隐藏元素. 
3 java后台根据图片关键的四个参数实现图片剪切并在服务器端生成图片文件 
4 通过生成图片的地址在前台展现
 
开发环境: XP3 
开发工具: JDK1.6+MyEclipse6.5+Tomcat6
 
工程图片: 
 
三 实现方式 
1 选用JQuery插件:Jcrop 
官方网站: http://deepliquid.com/content/Jcrop.html  
项目地址: http://code.google.com/p/jcrop/  
效果图片如下: 
 
2 通过图片剪切工具类,主要代码如下: 
Java代码   收藏代码
  1. /**  
  2.      * 图像切割(改)     *  
  3.      * @param srcImageFile            源图像地址 
  4.      * @param dirImageFile            新图像地址 
  5.      * @param x                       目标切片起点x坐标 
  6.      * @param y                      目标切片起点y坐标 
  7.      * @param destWidth              目标切片宽度 
  8.      * @param destHeight             目标切片高度 
  9.      */  
  10.     public static void abscut(String srcImageFile,String dirImageFile, int x, int y, int destWidth,  
  11.             int destHeight) {  
  12.         try {  
  13.             Image img;  
  14.             ImageFilter cropFilter;  
  15.             // 读取源图像  
  16.             BufferedImage bi = ImageIO.read(new File(srcImageFile));  
  17.             int srcWidth = bi.getWidth(); // 源图宽度  
  18.             int srcHeight = bi.getHeight(); // 源图高度            
  19.             if (srcWidth >= destWidth && srcHeight >= destHeight) {  
  20.                 Image image = bi.getScaledInstance(srcWidth, srcHeight,  
  21.                         Image.SCALE_DEFAULT);  
  22.                 // 改进的想法:是否可用多线程加快切割速度  
  23.                 // 四个参数分别为图像起点坐标和宽高  
  24.                 // 即: CropImageFilter(int x,int y,int width,int height)  
  25.                 cropFilter = new CropImageFilter(x, y, destWidth, destHeight);  
  26.                 img = Toolkit.getDefaultToolkit().createImage(  
  27.                         new FilteredImageSource(image.getSource(), cropFilter));  
  28.                 BufferedImage tag = new BufferedImage(destWidth, destHeight,  
  29.                         BufferedImage.TYPE_INT_RGB);  
  30.                 Graphics g = tag.getGraphics();  
  31.                 g.drawImage(img, 0, 0, null); // 绘制缩小后的图  
  32.                 g.dispose();  
  33.                 // 输出为文件  
  34.                 ImageIO.write(tag, "JPEG", new File(dirImageFile));  
  35.             }  
  36.         } catch (Exception e) {  
  37.             e.printStackTrace();  
  38.         }  
  39.     }  


四 具体代码如下: 
1 index.jsp(上传图片页面) 
Java代码   收藏代码
  1. <%@ page language="java" pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%>  
  2. <%  
  3. String path = request.getContextPath();  
  4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  5. %>  
  6. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  7. <html>  
  8.   <head>  
  9.     <base href="<%=basePath%>">      
  10.     <title></title>  
  11.     <meta http-equiv="pragma" content="no-cache">  
  12.     <meta http-equiv="cache-control" content="no-cache">  
  13.     <meta http-equiv="expires" content="0">         
  14.     <script src="/scripts/clearFile.js" type="text/javascript"></script>  
  15.     <script type="text/javascript">  
  16.       
  17.         /**检查图片上传类型*/         
  18.          function checkImgType(obj){  
  19.            
  20.           var imgFile = '';   
  21.           //获取图片的全路径  
  22.           var imgFilePath = getImgFullPath(obj);       
  23.           var endIndex = imgFilePath.lastIndexOf("\\");  
  24.           var lastIndex = imgFilePath.length-endIndex-1;  
  25.           if (endIndex != -1)  
  26.              imgFile= imgFilePath.substr(endIndex+1,lastIndex);  
  27.           else  
  28.              imgFile = imgFilePath;       
  29.               
  30.           var tag = true;              
  31.           endIndex = imgFilePath.lastIndexOf(".");             
  32.           if (endIndex == -1)   
  33.             tag = false;  
  34.               
  35.           var ImgName = imgFilePath.substr(endIndex+1,lastIndex);  
  36.           ImgName = ImgName.toUpperCase();          
  37.            
  38.           if (ImgName !="GIF" && ImgName !="JPG" && ImgName !="PNG" && ImgName !="BMP"){   
  39.               tag=false;  
  40.           }  
  41.           if (!tag) {  
  42.               alert("上传图片的文件类型必须为: *.gif,*.jpg,*.png,*.bmp,请重新选择!")  
  43.               Upload.clear(obj);                       
  44.               return false;  
  45.           }     
  46.           document.form1.submit();  
  47.       }  
  48.           
  49.         function getImgFullPath(obj) {  
  50.             if (obj) {    
  51.                //ie    
  52.                if (window.navigator.userAgent.indexOf("MSIE") >= 1) {    
  53.                    obj.select();    
  54.                    return document.selection.createRange().text;    
  55.                }    
  56.                //firefox    
  57.                else if (window.navigator.userAgent.indexOf("Firefox") >= 1) {    
  58.                    if (obj.files) {    
  59.                        return obj.files.item(0).getAsDataURL();    
  60.                    }    
  61.                    return obj.value;    
  62.                }           
  63.                return obj.value;    
  64.            }    
  65.         }   
  66.     </script>  
  67.       
  68.   </head>    
  69.   <body>  
  70.     <form name=form1 method=post enctype="multipart/form-data" action="<%=path%>/imgUpload">  
  71.         <div style="margin-left: 35%;margin-top: 20%">  
  72.         <table width="100%" border="0" align="center" cellpadding="0" cellspacing="0" >            
  73.           <tr>                
  74.                <td >&nbsp;图片上传<font color='red'>*.gif,*.jpg,*.png,*.bmp</font></td>                
  75.            </tr>    
  76.            <tr>     
  77.                <td width="80%">                 
  78.                  <input type="file" name="imgFile" id="imgFile" maxlength="160" onchange="checkImgType(this);" width="300px"/>&nbsp;                         
  79.                </td>      
  80.            </tr>                 
  81.         </table>    
  82.        </div>  
  83.     </form>  
  84.   </body>  
  85. </html>  

2 ImgUploadServlet.java(图片上传处理类) 
Java代码   收藏代码
  1. import java.awt.image.BufferedImage;  
  2. import java.io.File;  
  3. import java.io.IOException;  
  4. import java.text.SimpleDateFormat;  
  5. import java.util.Date;  
  6.   
  7. import javax.imageio.ImageIO;  
  8. import javax.servlet.ServletException;  
  9. import javax.servlet.http.HttpServlet;  
  10. import javax.servlet.http.HttpServletRequest;  
  11. import javax.servlet.http.HttpServletResponse;  
  12.   
  13.   
  14. public class ImgUploadServlet extends HttpServlet {  
  15.   
  16.   
  17.     private static final long serialVersionUID = 1L;  
  18.     public static final String IMGROOT = "/uploads/";  
  19.       
  20.     public void doGet(HttpServletRequest request, HttpServletResponse response)  
  21.             throws ServletException, IOException {  
  22.         doPost(request,response);  
  23.     }  
  24.   
  25.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
  26.             throws ServletException, IOException {  
  27.       
  28.         String userWebAppPath = getWebAppPath();  
  29.         /**检查是否有图片上传文件夹*/  
  30.         checkImageDir(userWebAppPath);    
  31.           
  32.         /**图片上传的相对路径*/  
  33.         String imgUploadPath = null;  
  34.         String imgWebAppPath = null;  
  35.         /**图片后缀*/  
  36.         String imgFileExt = null;  
  37.           
  38.         /**图片名称:以当前日期*/  
  39.         SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddhhmmss");  
  40.         String imgFileId = formatter.format(new Date());  
  41.           
  42.         //图片初始化高度与宽度  
  43.         String width = null;  
  44.         String height = null;  
  45.           
  46.         int imgWidth = 0;  
  47.         int imgHeight = 0;  
  48.   
  49.         try {  
  50.               
  51.             com.jspsmart.upload.SmartUpload smartUpload = new com.jspsmart.upload.SmartUpload();  
  52.             smartUpload.initialize(getServletConfig(), request, response);  
  53.             smartUpload.upload();  
  54.             com.jspsmart.upload.Request rqest = smartUpload.getRequest();  
  55.               
  56.             //指定图片宽度和高度  
  57.             width = rqest.getParameter("width");  
  58.             if(null == width){  
  59.                 width = "700";  
  60.             }  
  61.             height= rqest.getParameter("height");     
  62.             if(null == height){  
  63.                 height = "600";  
  64.             }  
  65.               
  66.             imgWidth = Integer.parseInt(width);  
  67.             imgHeight = Integer.parseInt(height);  
  68.               
  69.               
  70.             //文件个数  
  71.             int fileCounts =  smartUpload.getFiles().getCount();      
  72.           
  73.             for (int i = 0; i <fileCounts; i++) {  
  74.                 com.jspsmart.upload.File myFile = smartUpload.getFiles().getFile(i);  
  75.                   
  76.                 if (!myFile.isMissing()) {  
  77.                       
  78.                     imgFileExt = myFile.getFileExt();  
  79.                     //组装图片真实名称  
  80.                     imgFileId += i + System.currentTimeMillis() + "." + imgFileExt;  
  81.                       
  82.                     //图片生成路径  
  83.                     imgWebAppPath = userWebAppPath + imgFileId;  
  84.                       
  85.                     //生成图片文件  
  86.                     myFile.saveAs(imgWebAppPath);  
  87.                     //图片的相对路径  
  88.                     imgUploadPath = IMGROOT + imgFileId;  
  89.                       
  90.                     //检查图片大小  
  91.                     BufferedImage src = ImageIO.read(new File(imgWebAppPath)); // 读入文件                         
  92.                     int imgSrcWidth = src.getWidth(); // 得到源图宽                             
  93.                     //重新指定大小  
  94.                     imgWidth = imgSrcWidth > imgWidth ? imgWidth : imgSrcWidth;  
  95.                       
  96.                     int imgSrcHeight = src.getHeight(); // 得到源图长  
  97.                     imgHeight = imgSrcHeight > imgHeight ? imgHeight : imgSrcHeight;  
  98.                   
  99.                     //按照图片的设置大小生成  
  100.                     ImageCut.scale(imgWebAppPath, imgWebAppPath,imgWidth,imgHeight);  
  101.                      File f = new File(imgWebAppPath);                                
  102.                      if(f.exists()){                          
  103.                          System.out.println("创建"+imgWidth+"*"+imgHeight+"图片成功");  
  104.                      }                    
  105.                 }  
  106.                   
  107.             }  
  108.               
  109.         }catch(Exception ex){  
  110.             ex.printStackTrace();  
  111.         }  
  112.           
  113.         String path = "/imgcrop.jsp?tag=0&oldImgPath="+imgUploadPath+"&imgFileExt="+imgFileExt+"&imgRoot="+IMGROOT+"&width="+imgWidth+"&height="+imgHeight;  
  114.         System.out.println("path: "+path);  
  115.         request.getRequestDispatcher(path).forward(request,response);  
  116.           
  117.     }  
  118.       
  119.     private String getWebAppPath(){  
  120.         String webAppPath = this.getServletContext().getRealPath("/");        
  121.         String userWebAppPath = webAppPath+IMGROOT;  
  122.         return userWebAppPath;  
  123.     }  
  124.   
  125.     private void checkImageDir(String userWebAppPath) {       
  126.          File file = new File(userWebAppPath);  
  127.          if(!file.exists()){  
  128.              file.mkdir();  
  129.          }  
  130.     }  
  131. }  

3 imgcrop.jsp(图片展现并剪切页面) 
Java代码   收藏代码
  1. <%@ page language="java"  pageEncoding="UTF-8"%>  
  2. <%  
  3. String path = request.getContextPath();  
  4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  5. %>  
  6. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>  
  7. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  8. <html>  
  9.   <head>  
  10.     <base href="<%=basePath%>">      
  11.     <title>图片剪辑</title>      
  12.     <meta http-equiv="pragma" content="no-cache">  
  13.     <meta http-equiv="cache-control" content="no-cache">  
  14.     <meta http-equiv="expires" content="0">      
  15.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  16.     <meta http-equiv="description" content="This is my page">  
  17.     <link rel="stylesheet" href="styles/jquery.Jcrop.css" type="text/css" />  
  18.     <link rel="stylesheet" href="styles/demos.css" type="text/css" />   
  19.     <script src="scripts/jquery.min.js"></script>  
  20.     <script src="scripts/jquery.Jcrop.js"></script>       
  21.   </head>    
  22.  <body STYLE='OVERFLOW:SCROLL;OVERFLOW-X:HIDDEN;OVERFLOW-Y:HIDDEN'>  
  23.       
  24.     <form name=form1 method=post action="<%=path%>/imgCrop">  
  25.           
  26.         <table width="60%" border="0" align="center" cellpadding="0" cellspacing="0" >             
  27.            <tr>      
  28.                <td id="cropTd" style="display:none"><input type="button" value="剪切照片" id="cropButton"/></td>      
  29.            </tr>     
  30.              
  31.             <tr>                
  32.               <td id="imgTd" style="width:${param.width}px;height:${param.height}px;" align="center" style="padding-top:5px;">      
  33.                  <c:choose>  
  34.                     <c:when test="${param.tag eq 0}">  
  35.                         <img  src="<%=path%>${param.oldImgPath}" id="imgCrop" name="imgCrop" border="0" />       
  36.                     </c:when>  
  37.                     <c:when test="${param.tag eq 1}">  
  38.                         <img  src="<%=path%>${param.imgName}" id="imgCrop" name="imgCrop" border="0" />      
  39.                     </c:when>  
  40.                  </c:choose>    
  41.             </td>                 
  42.            </tr>   
  43.                
  44.             <tr>    
  45.                <td>  
  46.                      <label>X1 <input type="text" size="4" id="labelX" name="labelX" /></label>  
  47.                     <label>Y1 <input type="text" size="4" id="labelY" name="labelY" /></label>  
  48.                     <label>X2 <input type="text" size="4" id="labelX2" name="labelX2" /></label>  
  49.                     <label>Y2 <input type="text" size="4" id="labelY2" name="labelY2" /></label>  
  50.                     <label>W <input type="text" size="4" id="labelW" name="labelW" /></label>  
  51.                     <label>H <input type="text" size="4" id="labelH" name="labelH" /></label>  
  52.                </td>      
  53.            </tr>  
  54.              
  55.             <tr>    
  56.                <td  colspan="2"><a href="index.jsp">返回上传图片</a></td>      
  57.            </tr>              
  58.      </table>  
  59.       
  60.     <input type="hidden"  id="x" name="x" />  
  61.     <input type="hidden"  id="y" name="y" />  
  62.     <input type="hidden"  id="x2" name="x2" />  
  63.     <input type="hidden"  id="y2" name="y2" />  
  64.     <input type="hidden"  id="w" name="w" />  
  65.     <input type="hidden"  id="h" name="h" />    
  66.       
  67.     <!-- 源图片宽度和高度 -->  
  68.     <input type="hidden"  id="width" name="width" value="${param.width}"/>    
  69.     <input type="hidden"  id="height" name="height" value="${param.height}"/>  
  70.     <input type="hidden"  id="oldImgPath" name="oldImgPath" value="${param.oldImgPath}"/>    
  71.     <input type="hidden"  id="imgRoot" name="imgRoot" value="${param.imgRoot}"/>    
  72.     <input type="hidden"  id="imgFileExt" name="imgFileExt" value="${param.imgFileExt}"/>   
  73.       
  74.     </form>  
  75.   </body>  
  76. </html>  
  77. <script type="text/javascript">  
  78.   
  79.     jQuery(document).ready(function(){        
  80.       
  81.           
  82.         jQuery('#imgCrop').Jcrop({  
  83.             onChange: showCoords,  
  84.             onSelect: showCoords  
  85.         });   
  86.           
  87.         jQuery('#cropButton').click(function(){  
  88.                 var x = jQuery("#x").val();  
  89.                 var y = jQuery("#y").val();  
  90.                 var w = jQuery("#w").val();  
  91.                 var h = jQuery("#h").val();           
  92.                   
  93.                 if(w == 0 || h == 0 ){  
  94.                     alert("您还没有选择图片的剪切区域,不能进行剪切图片!");  
  95.                     return;  
  96.                 }     
  97.                 alert("你要剪切图片的X坐标: "+x + ",Y坐标: " + y + ",剪切图片的宽度: " + w + ",高度:" + h );  
  98.                 if(confirm("确定按照当前大小剪切图片吗")){                 
  99.                     document.form1.submit();  
  100.                 }  
  101.          });  
  102.           
  103.       
  104.     });  
  105.       
  106.     function showCoords(c)  
  107.     {  
  108.         jQuery('#x').val(c.x);  
  109.         jQuery('#y').val(c.y);  
  110.         jQuery('#x2').val(c.x2);  
  111.         jQuery('#y2').val(c.y2);  
  112.         jQuery('#w').val(c.w);  
  113.         jQuery('#h').val(c.h);    
  114.           
  115.         jQuery('#labelX').val(c.x);  
  116.         jQuery('#labelY').val(c.y);  
  117.         jQuery('#labelX2').val(c.x2);  
  118.         jQuery('#labelY2').val(c.y2);  
  119.         jQuery('#labelW').val(c.w);  
  120.         jQuery('#labelH').val(c.h);   
  121.           
  122.         //显示剪切按键  
  123.         jQuery('#cropTd').css("display","");  
  124.                   
  125.     }  
  126. </script>  

4 ImgCropServlet.java(执行图片剪切类) 
Java代码   收藏代码
  1. import java.io.File;  
  2. import java.io.IOException;  
  3. import java.text.SimpleDateFormat;  
  4. import java.util.Date;  
  5.   
  6. import javax.servlet.ServletException;  
  7. import javax.servlet.http.HttpServlet;  
  8. import javax.servlet.http.HttpServletRequest;  
  9. import javax.servlet.http.HttpServletResponse;  
  10.   
  11. public class ImgCropServlet extends HttpServlet {  
  12.   
  13.     private static final long serialVersionUID = 1L;  
  14.   
  15.     public void doGet(HttpServletRequest request, HttpServletResponse response)  
  16.             throws ServletException, IOException {  
  17.         doPost(request, response);  
  18.   
  19.     }  
  20.   
  21.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
  22.             throws ServletException, IOException {  
  23.           
  24.         System.out.println("x: " + request.getParameter("x") + "," + request.getParameter("y") + "," + request.getParameter("w") + "," + request.getParameter("h"));  
  25.   
  26.         // 用户经过剪辑后的图片的大小  
  27.         Integer x = Integer.parseInt(request.getParameter("x"));  
  28.         Integer y = Integer.parseInt(request.getParameter("y"));  
  29.         Integer w = Integer.parseInt(request.getParameter("w"));  
  30.         Integer h = Integer.parseInt(request.getParameter("h"));  
  31.           
  32.         //获取原显示图片路径  
  33.         String oldImgPath = request.getParameter("oldImgPath");  
  34.         //图片后缀  
  35.         String imgFileExt = request.getParameter("imgFileExt");  
  36.         String imgRoot =  request.getParameter("imgRoot");  
  37.           
  38.         Integer width = Integer.parseInt(request.getParameter("width"));  
  39.         Integer height = Integer.parseInt(request.getParameter("height"));  
  40.           
  41.         //WEB应用程序根路径  
  42.         String webAppPath = getServletContext().getRealPath("/");  
  43.           
  44.         /**图片名称:以当前日期*/  
  45.         SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddhhmmss");  
  46.         String imgFileId = formatter.format(new Date());  
  47.         String imgName =  imgRoot + imgFileId + System.currentTimeMillis() + "." + imgFileExt;            
  48.         //组装图片真实名称  
  49.         String createImgPath = webAppPath + imgName;  
  50.           
  51.         //之前上传的图片路径  
  52.         webAppPath += oldImgPath;  
  53.           
  54.         System.out.println("原图片路径: " + webAppPath + ",新图片路径: " + createImgPath);  
  55.           
  56.         //进行剪切图片操作  
  57.         ImageCut.abscut(webAppPath, createImgPath, x,y,w, h);  
  58.           
  59.          File f = new File(createImgPath);                                
  60.          if(f.exists()){                          
  61.              System.out.println("剪切图片大小: "+w+"*"+h+"图片成功!");  
  62.          }    
  63.            
  64.         String path = "/imgcrop.jsp?tag=1&oldImgPath="+oldImgPath+"&imgFileExt="+imgFileExt+"&imgRoot="+imgRoot + "&imgName="+imgName+"&height=" + height + "&width=" + width;  
  65.         System.out.println("imgCrop: " + path);  
  66.         request.getRequestDispatcher(path).forward(request,response);  
  67.     }  
  68.   
  69. }  

5 ImageCut.java(图片剪切工具类) 
Java代码   收藏代码
  1. import java.io.*;  
  2. import java.awt.*;  
  3. import java.awt.image.*;  
  4. import java.awt.Graphics;  
  5. import java.awt.color.ColorSpace;  
  6. import javax.imageio.ImageIO;  
  7.   
  8. public class ImageCut {  
  9.       
  10.     /**  
  11.      * 图像切割(改)     *  
  12.      * @param srcImageFile            源图像地址 
  13.      * @param dirImageFile            新图像地址 
  14.      * @param x                       目标切片起点x坐标 
  15.      * @param y                      目标切片起点y坐标 
  16.      * @param destWidth              目标切片宽度 
  17.      * @param destHeight             目标切片高度 
  18.      */  
  19.     public static void abscut(String srcImageFile,String dirImageFile, int x, int y, int destWidth,  
  20.             int destHeight) {  
  21.         try {  
  22.             Image img;  
  23.             ImageFilter cropFilter;  
  24.             // 读取源图像  
  25.             BufferedImage bi = ImageIO.read(new File(srcImageFile));  
  26.             int srcWidth = bi.getWidth(); // 源图宽度  
  27.             int srcHeight = bi.getHeight(); // 源图高度            
  28.             if (srcWidth >= destWidth && srcHeight >= destHeight) {  
  29.                 Image image = bi.getScaledInstance(srcWidth, srcHeight,  
  30.                         Image.SCALE_DEFAULT);  
  31.                 // 改进的想法:是否可用多线程加快切割速度  
  32.                 // 四个参数分别为图像起点坐标和宽高  
  33.                 // 即: CropImageFilter(int x,int y,int width,int height)  
  34.                 cropFilter = new CropImageFilter(x, y, destWidth, destHeight);  
  35.                 img = Toolkit.getDefaultToolkit().createImage(  
  36.                         new FilteredImageSource(image.getSource(), cropFilter));  
  37.                 BufferedImage tag = new BufferedImage(destWidth, destHeight,  
  38.                         BufferedImage.TYPE_INT_RGB);  
  39.                 Graphics g = tag.getGraphics();  
  40.                 g.drawImage(img, 0, 0, null); // 绘制缩小后的图  
  41.                 g.dispose();  
  42.                 // 输出为文件  
  43.                 ImageIO.write(tag, "JPEG", new File(dirImageFile));  
  44.             }  
  45.         } catch (Exception e) {  
  46.             e.printStackTrace();  
  47.         }  
  48.     }  
  49.   
  50.       
  51.     /** 
  52.      * 缩放图像 
  53.      *  
  54.      * @param srcImageFile       源图像文件地址 
  55.      * @param result             缩放后的图像地址 
  56.      * @param scale              缩放比例 
  57.      * @param flag               缩放选择:true 放大; false 缩小; 
  58.      */  
  59.     public static void scale(String srcImageFile, String result, int scale,  
  60.             boolean flag) {  
  61.         try {  
  62.             BufferedImage src = ImageIO.read(new File(srcImageFile)); // 读入文件  
  63.             int width = src.getWidth(); // 得到源图宽  
  64.             int height = src.getHeight(); // 得到源图长  
  65.             if (flag) {  
  66.                 // 放大  
  67.                 width = width * scale;  
  68.                 height = height * scale;  
  69.             } else {  
  70.                 // 缩小  
  71.                 width = width / scale;  
  72.                 height = height / scale;  
  73.             }  
  74.             Image image = src.getScaledInstance(width, height,Image.SCALE_DEFAULT);  
  75.             BufferedImage tag = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);  
  76.             Graphics g = tag.getGraphics();  
  77.             g.drawImage(image, 0, 0, null); // 绘制缩小后的图  
  78.             g.dispose();  
  79.             ImageIO.write(tag, "JPEG", new File(result));// 输出到文件流  
  80.         } catch (IOException e) {  
  81.             e.printStackTrace();  
  82.         }  
  83.     }  
  84.       
  85.     /** 
  86.      * 重新生成按指定宽度和高度的图像 
  87.      * @param srcImageFile       源图像文件地址 
  88.      * @param result             新的图像地址 
  89.      * @param _width             设置新的图像宽度 
  90.      * @param _height            设置新的图像高度 
  91.      */  
  92.     public static void scale(String srcImageFile, String result, int _width,int _height) {        
  93.         scale(srcImageFile,result,_width,_height,0,0);  
  94.     }  
  95.       
  96.     public static void scale(String srcImageFile, String result, int _width,int _height,int x,int y) {  
  97.         try {  
  98.               
  99.             BufferedImage src = ImageIO.read(new File(srcImageFile)); // 读入文件  
  100.               
  101.             int width = src.getWidth(); // 得到源图宽  
  102.             int height = src.getHeight(); // 得到源图长  
  103.               
  104.             if (width > _width) {  
  105.                  width = _width;  
  106.             }  
  107.             if (height > _height) {  
  108.                 height = _height;  
  109.             }             
  110.             Image image = src.getScaledInstance(width, height,Image.SCALE_DEFAULT);  
  111.             BufferedImage tag = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);  
  112.             Graphics g = tag.getGraphics();  
  113.             g.drawImage(image, x, y, null); // 绘制缩小后的图  
  114.             g.dispose();              
  115.             ImageIO.write(tag, "JPEG", new File(result));// 输出到文件流  
  116.         } catch (IOException e) {  
  117.             e.printStackTrace();  
  118.         }  
  119.     }  
  120.       
  121.     /** 
  122.      * 图像类型转换 GIF->JPG GIF->PNG PNG->JPG PNG->GIF(X) 
  123.      */  
  124.     public static void convert(String source, String result) {  
  125.         try {  
  126.             File f = new File(source);  
  127.             f.canRead();  
  128.             f.canWrite();  
  129.             BufferedImage src = ImageIO.read(f);  
  130.             ImageIO.write(src, "JPG", new File(result));  
  131.         } catch (Exception e) {  
  132.             e.printStackTrace();  
  133.         }  
  134.     }  
  135.   
  136.     /** 
  137.      * 彩色转为黑白 
  138.      *  
  139.      * @param source 
  140.      * @param result 
  141.      */  
  142.     public static void gray(String source, String result) {  
  143.         try {  
  144.             BufferedImage src = ImageIO.read(new File(source));  
  145.             ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);  
  146.             ColorConvertOp op = new ColorConvertOp(cs, null);  
  147.             src = op.filter(src, null);  
  148.             ImageIO.write(src, "JPEG", new File(result));  
  149.         } catch (IOException e) {  
  150.             e.printStackTrace();  
  151.         }  
  152.     }     
  153. }  
jquery在线上传头像图片裁剪插件,后台转码插件类+页面实例打包整理 插件效果不错,自行进行了整合,此插件需要向后台传送base64编码,而后进行转码处理 ,已经将转码插件 图片保存插件一并打包导入即可使用 立即下载

相关推荐

js+jquery+java实现的头像上传和裁剪

js+jquery+java实现的头像上传和裁剪,界面仿百度头像上传样式,完美兼容各种浏览器,集成java上传技术+java图像处理+js剪切图片效果+jquery无刷新上传文件

html+JavaScript实现头像框及上传剪裁功能

【代码】html+JavaScript实现头像框及上传剪裁功能。

Jukomu的博客 578

Jquery的Cropper头像剪切

利用Jquery的cropper插件实现拖动层动态头剪切(裁剪头像)图片,并且做了一定的优化。

基于Jquery/cropper插件的使用。头像截切/裁剪图片。

—-》闲来无事,学习了解一点新的东西还是可以消磨时间,非常敬业、提炼升仙。本栗针对移动页面上需要头像裁剪上传的功能。 基于Jquery库/Cropper插件 实现头像旋转、裁剪、转换canvas等功能。模仿QQ头像上传的样式,具体使用方法请参考如下实例。使用方法: 1、引入插件需要的js、css文件即可。请jquery文件放在cropper.js前面引用。&lt;link rel=&quot;styleshe

China_Guanq的博客 1557

jQuery点击头像上传本地预览裁剪图片

使用jquery上传前,预览图片,裁剪,示例使用php接收上传的文件,并且保存为裁剪后的图片。不需要上传后再裁剪图片,只需要本地裁剪好即可,裁剪的时候也可以旋转图片。

适用于移动端网页上传裁剪图片功能插件.zip

效果描述: 非常适合移动网页的图片上传裁剪效果 缺点就是调用的js文件比较多 使用方法: 1、将CSS样式拷贝到你的网页中 2、将body中需要的代码部分拷贝到你需要的地方即可

用JQuery仿造QQ头像裁剪功能

最近工作真心忙碌,几乎没时间写博客。今天趁周末来仿一个QQ头像裁剪功能插件。效果如下: 所有文件都可在我的Github上下载,从头到尾从简到繁按步骤一共分了9个HTML文件,每个步骤文件里的注释都写的很清楚,故在本博客内不赘述。 原理: 主要是通过css的clip来裁剪图片可视区域,拖动剪裁窗口这里使用了JQ-UI的draggable插件(但是缩放没有,贪方便可以使用Res...

dcof99817的博客 302

基于紫光展锐平台的音频调用到hal层逻辑

基于紫光展锐平台的音频调用到hal层逻辑 1、数据流程图 AudioPolicyService和AudioFlinger的创建: 这两个服务都在audioserver中启动,文件路径: frameworks/av/media/audioserver/main_audioserver.cpp 从AudioFlinger和AudioPolicyService的创建,到output的打开,以及AudioFlinger开始往底层写入数据的具体流程如下图: #mermaid-svg-kjHL4XWwkQXN6NdA

weixin_55053963的博客 1355

jquery 图片裁剪 java_jQuery与Java实现图片的剪切

http://terje.blog.163.com/blog/static/11924371201101311319664/2 javascript+java截取图像,图像处理http://www.blogjava.net/b47248054/articles/200685.html3 js+java 截取照片中的头像http://blog.youkuaiyun.com/dsj188/article/deta...

weixin_31193137的博客 394

OCC WebGL案例编译实战:从FreeType配置到静态库生成

本文详细记录了将OCC(Open CASCADE Technology)3D图形库编译为WebAssembly(Wasm)并在浏览器中通过WebGL渲染的实战过程。重点解决了FreeType库的交叉编译配置、OCC核心库的裁剪与静态库生成,以及WebGL样例项目的CMake改造等关键步骤,为开发者提供了从环境搭建到最终集成的完整指南。

weixin_28831461的博客 315

缺陷检测-金属表面缺陷检测

1介绍 缺陷检测是工业视觉技术中最重要的组成部分。业务广泛,场景丰富,技术难点高、工作量大。针对不同的场景,选择不同的相机和

huneng1991的专栏 5248

jQuery与Java实现图片的剪切---资料总结

一 参考资料  1 jquery Jcrop 头像,logo截图   http://terje.blog.163.com/blog/static/11924371201101311319664/  2 javascript+java截取图像,图像处理  http://www.blogjava.net/b47248054/articles/200685.html  3 js+java 截取

holeeye的专栏 812

scDeepCluster_pytorch代码解读与文章理解

论文:Clustering single-cell RNA-seq data with a。

qq_34179307的博客 914

利用jQuery与Java实现在线图片的剪切

一 参考资料 1 jquery Jcrop 头像,logo截图 http://terje.blog.163.com/blog/static/11924371201101311319664/ 2 javascript+java截取图像,图像处理 http:...

chuge6367的博客 122

飞思卡尔16位单片机(二)——CodeWarrior开发环境搭建及新建、调试工程

一、安装CodeWarrior 飞思卡尔16位单片机的开发环境为CodeWarrior5.1,这个软件安装比较简单,软件的安装文件可以从相应的网站上下载。安装CodeWarrior所需要的电脑的硬件资源也比较宽泛,目前一般的电脑都可以满足这个要求,可以支持win10、win7等操作系统。安装过程按照按照软件的提示一步步操作即可。 二、安装USBDM驱动 USBDM是...

bigmarshal的博客 1万+

Linux下的隐藏技术(文件隐藏、进程隐藏、端口隐藏、权限隐藏、命令隐藏)

这种技巧是关键记录删除,或者我们可以暴力点,比如前150行是用户的正常操作记录,150以后是攻击者操作记录。在Linux中,使用chattr命令来防止root和其他管理用户误删除和修改重要文件及目录,此权限用ls -l是查看不出来的,从而达到隐藏权限的目的。上面的命令会临时禁用历史功能,这意味着在这命令之后你执行的所有操作都不会记录到历史中,然而这个命令之前的所有东西都会原样记录在历史列表中。这种情况下我们怎么办?在shell中执行的命令,不希望被记录在命令行历史中,如何在linux中开启无痕操作模式呢?

墨痕诉清风的博客 744

js+java实现的头像上传和裁剪,完美兼容各种浏览器

js+jquery+java实现头像剪切上传,页面样式仿百度头像上传布局,界面美观大方

wqj975005563的专栏 1万+

【agent实操】OpenClaw玩转股票分析多个AI智能体(agent)出谋划策

本文介绍了一个基于OpenClaw的多Agent股票分析系统。该系统采用"三人组+总调度"模式,包含三个核心Agent:小牛马(策略中枢)、牛老二(基本面分析师)和牛老三(技术面分析师)。相比单Agent模式,该系统具有分析更专业、权限分级更安全、成本控制更优等优势。文章详细说明了系统部署的6个步骤,包括创建独立Agent工作区、配置专属人设与技能等,并提供了环境检查命令和验证方法。通过这种多Agent协作的方式,可以实现更专业、更安全的股票分析。

海兰 807

java上传头像图像剪切

java上传头像图像剪切 JQUERY 图片上传裁切

chengyue2007的专栏 240

用 SAP-ABAP-1 把 ABAP 代码理解这件事交给 AI:从遗留代码到 ABAP Cloud 的开发加速器

SAP-ABAP-1是SAP推出的首个专用ABAP基础模型,专注于理解和解释ABAP代码,帮助开发者更快迁移和维护遗留系统。它强调ABAP Cloud合规编码实践,通过SAP AI Foundation提供访问,主要能力包括代码解释、业务语义理解和框架约束分析。相比通用模型,它能更好处理ABAP特有的版本差异、权限控制和扩展边界等问题。该模型可集成到多种开发环境中,支持文件化开发体验,并能与SAP Joule等工具协同工作,为ABAP团队提供智能辅助。

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 3823

最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版

Part-E1-SDIO-Specification-Ver4.00-Final-120220.pdf:最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版,包括SDIO 接口的外设,SDIO 接口官方协议等。

Struts2 图片上传、缩放、剪切处理 第二节

Struts2 图片上传、缩放、剪切处理 第一节   Struts2 图片上传、缩放、剪切处理 第二节   1、技术目标:   对上传的图片进行缩放、剪切操作   提示:本文示例项目已提供下载 2、处理流程: 1)在影片列表页面(films.jsp)点"修改"进入影片修改页面,如图:     2)在影片修改页面(update.jsp)中双击图片,进入图片缩...

Java软件工程师之路 194

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

上一篇: Jxl导出Excel(跨行、设置列宽、设置行高、自动对齐、自定义背景等)
下一篇: java substring 截取
OnePiece_Sky
博客等级 码龄15年 9粉丝 63原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值