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 截取照片中的头像 
http://blog.csdn.net/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
 
工程图片: 
jQuery与Java实现图片的剪切_第1张图片  
三 实现方式 
1 选用JQuery插件:Jcrop 
官方网站: http://deepliquid.com/content/Jcrop.html  
项目地址: http://code.google.com/p/jcrop/  
效果图片如下: 
jQuery与Java实现图片的剪切_第2张图片  
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, 00null); // 绘制缩小后的图  
  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, 00null); // 绘制缩小后的图  
  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, 00null); // 绘制缩小后的图  
  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与Java实现图片的剪切)