`

ImageUtil(图片处理工具类,压缩,复制,附件等)

    博客分类:
  • java
 
阅读更多

 

内容含:图片处理工具类;以图片压缩为例 ,编写调用实例

 

第一步:框架中加入配置文件application.properties图片压缩后指定的高宽在此配置文件中配置

内容为:

 

Xml代码  收藏代码
  1. image.width=150  
  2. image.height=150  

 

 

第二步:框架中加入配置文件加载操作类,详情见:http://lucien-zzy.iteye.com/admin/blogs/2009495

 

第三步:编写图片处理工具类

 

Java代码  收藏代码
  1. /** 
  2.  * 图片处理工具 
  3.  * @author ziyuzhang 
  4.  * 
  5.  */  
  6. public class ImageUtil {  
  7.   
  8.     private static final int BUFFER_SIZE = 16 * 1024;  
  9.   
  10.       
  11.       
  12.     /** 
  13.      * 处理图片并保存  一张原图和一张缩小后的图片  小图可用于手机端 
  14.      * @param upload             大图对象 
  15.      * @param uploadFileName     图片原名 
  16.      * @param webPath            工程部署的绝对地址 
  17.      * @param filePath           图片目录 
  18.      * @return   为一字符数字,0位置 为原图片位置,1位置为压缩后图片位置,2位置为压缩后图片高度,3位置为压缩后图片宽度,4位置为压缩后图片大小 
  19.      */  
  20.     public static String[] uploadImages(File upload, String uploadFileName,String webPath,String filePath) {  
  21.   
  22.         StringTokenizer tokenizer = new StringTokenizer(uploadFileName, ".");  
  23.         String ext="";  
  24.         while(tokenizer.hasMoreTokens()){  
  25.             ext = tokenizer.nextToken();  
  26.         }  
  27.           
  28.         //大图的名字  
  29.         String filename = ImageUtil.getUUID()+"."+ext;  
  30.         //保存大图  
  31.          if(!ImageUtil.saveFile(upload,webPath,filePath,filename)){  
  32.              return null;  
  33.          }  
  34.               
  35.         String afterFileName = ImageUtil.getUUID();  
  36.         //小图的名字  
  37.         String smallname =   afterFileName + "." + ext;  
  38.         String smallPath = webPath + filePath + smallname;   
  39.         // 产生一张新的截图  
  40.         String[] fileinfo =  ImageUtil.resizeImage(upload, smallPath,ConfigUtil.getIntValue("image.width"),   
  41.                 ConfigUtil.getIntValue("image.height"),ext);  
  42.         if(null == fileinfo){  
  43.             return new String[]{"/" + filePath + filename,"/" + filePath + filename,  
  44.                      null,null,null};  
  45.         }else{  
  46.             return new String[]{"/" + filePath + filename,"/" + filePath + smallname,  
  47.                                  fileinfo[0],fileinfo[1],fileinfo[2]};  
  48.         }  
  49.           
  50.     }  
  51.       
  52.     /** 
  53.      * 对应图片key为 upload 
  54.      * 保存附件 限制大小100M 
  55.      * @param response 
  56.      * @param request 
  57.      * @return 
  58.      */  
  59.        public static String getfile(HttpServletResponse  response,HttpServletRequest  request) {  
  60.   
  61.               
  62.              SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");  
  63.              // 根据服务器的文件保存地址找到项目部署的绝对地址  
  64.              String webPath = ServletActionContext.getServletContext().getRealPath("/")  ;  
  65.              String filePath ="upload/"+sdf.format(new Date())+"/";   
  66.             //文件保存目录路径  
  67.             String savePath = webPath+ "upload/";  
  68.             //最大文件大小  
  69.             long maxSize = 1024*1024*100;  
  70.             response.setContentType("text/html; charset=UTF-8");  
  71.             if (!ServletFileUpload.isMultipartContent(request)) {     
  72.                 return "erro";  
  73.             }  
  74.             //如果目录不存在则创建  
  75.             if (!(new File(savePath).exists())) {             
  76.                 if (!(new File(savePath).mkdirs())) {  
  77.                     return "erro";  
  78.                 }  
  79.             }   
  80.           
  81.             //检查目录写权限  
  82.             if (!(new File(savePath)).canWrite()) {  
  83.                 return "erro";  
  84.             }     
  85.             MultiPartRequestWrapper   mul = (MultiPartRequestWrapper)request;  
  86.             File[] imageFiles = mul.getFiles("upload");  
  87.             String[] filesss = mul.getFileNames("upload");        
  88.             if (imageFiles != null && imageFiles.length >0) {  
  89.   
  90.                 String fileName = filesss[0];  
  91.                 long fileSize = imageFiles[0].length();       
  92.                     //检查文件大小  
  93.                     if (fileSize > maxSize) {  
  94.                         return "erro";  
  95.                     }  
  96.                     //检查扩展名  
  97.                     String fileExt = fileName.substring(  
  98.                             fileName.lastIndexOf(".") + 1).toLowerCase();  
  99.                   
  100.                     SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");  
  101.                     String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;                
  102.                     //保存图片到硬盘  
  103.                     ImageUtil.saveFile(imageFiles[0], webPath, filePath, newFileName);                                
  104.                       
  105.                     filePath = webPath + filePath+newFileName ;  
  106.             }         
  107.               
  108.             return filePath;  
  109.         }  
  110.       
  111.   
  112.       
  113.     /** 
  114.      * 将文件保存到制定位置,路径不存在自动创建 
  115.      *  
  116.      * @param file 
  117.      *            要保存的文件 
  118.      * @param webPath 
  119.      *            工程部署的绝对路径 
  120.      * @param filePath 
  121.      *            文件夹的相对路径 
  122.      * @param filename 
  123.      *            文件名 
  124.      * @return 
  125.      */  
  126.     public static boolean saveFile(File file, String webPath, String filePath,  
  127.             String filename) {  
  128.   
  129.         if (new File(webPath + filePath).exists()) {  
  130.             webPath = webPath + filePath + "/" + filename;  
  131.             File dstFile = new File(webPath);  
  132.             if (copy(file, dstFile)) {  
  133.                 return true;  
  134.             }  
  135.   
  136.         } else {  
  137.             if (new File(webPath + filePath).mkdirs()) {  
  138.                 webPath = webPath + filePath + "/" + filename;  
  139.                 File dstFile = new File(webPath);  
  140.                 if (copy(file, dstFile)) {  
  141.                     return true;  
  142.                 }  
  143.   
  144.             }  
  145.   
  146.         }  
  147.         return false;  
  148.   
  149.     }  
  150.   
  151.     /** 
  152.      * 把源文件对象复制成目标文件对象 
  153.      *  
  154.      * @param src 
  155.      *            源文件 
  156.      * @param dst 
  157.      *            目标文件 
  158.      * @return 
  159.      */  
  160.     public static boolean copy(File src, File dst) {  
  161.         boolean result = false;  
  162.         InputStream in = null;  
  163.         OutputStream out = null;  
  164.         try {  
  165.             in = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE);  
  166.             out = new BufferedOutputStream(new FileOutputStream(dst),  
  167.                     BUFFER_SIZE);  
  168.             byte[] buffer = new byte[BUFFER_SIZE];  
  169.             int len = 0;  
  170.             while ((len = in.read(buffer)) > 0) {  
  171.                 out.write(buffer, 0, len);  
  172.             }  
  173.             result = true;  
  174.         } catch (Exception e) {  
  175.             e.printStackTrace();  
  176.             result = false;  
  177.         } finally {  
  178.             if (null != in) {  
  179.                 try {  
  180.                     in.close();  
  181.                 } catch (IOException e) {  
  182.                     e.printStackTrace();  
  183.                 }  
  184.             }  
  185.             if (null != out) {  
  186.                 try {  
  187.                     out.close();  
  188.                 } catch (IOException e) {  
  189.                     e.printStackTrace();  
  190.                 }  
  191.             }  
  192.         }  
  193.         return result;  
  194.     }  
  195.   
  196.     /** 
  197.      * 接收File输出图片 
  198.      * 以图片高为标准 按比例缩减图片 
  199.      * @param file 
  200.      *            原图片对象 
  201.      * @param writePath 
  202.      *            小图片存放的路径 
  203.      * @param width 
  204.      *            宽 
  205.      * @param height 
  206.      *            高 
  207.      * @param format 
  208.      *            图片格式 
  209.      * @return 
  210.      */  
  211.     public static String[]  resizeImage(File file, String writePath,  
  212.             Integer width, Integer height, String format) {  
  213.           
  214.         try {  
  215.             BufferedImage inputBufImage = ImageIO.read(file);  
  216.             inputBufImage.getType();  
  217.               
  218.             System.out.println("转前图片高度和宽度:" + inputBufImage.getHeight() + ":"  
  219.                     + inputBufImage.getWidth());  
  220.             if(height >=inputBufImage.getHeight() || width >= inputBufImage.getWidth()){  
  221.                   
  222.                 return null;  
  223.             }else{  
  224.             //double dd = inputBufImage.getHeight() / height;  
  225.             //width = (int) (inputBufImage.getWidth() / dd);  
  226.             //height = (int) (inputBufImage.getHeight() / dd);  
  227.             // 转换  
  228.             ResampleOp resampleOp = new ResampleOp(width, height);  
  229.             BufferedImage rescaledTomato = resampleOp.filter(inputBufImage,null);  
  230.             File fil = new File(writePath);  
  231.             ImageIO.write(rescaledTomato, format,fil);  
  232.             System.out.println("转后图片高度和宽度:" + rescaledTomato.getHeight() + ":"  
  233.                     + rescaledTomato.getWidth());  
  234.             return new String[]{rescaledTomato.getHeight()+"",rescaledTomato.getWidth()+"",fil.length()+""};  
  235.             }  
  236.         } catch (IOException e) {  
  237.             e.printStackTrace();  
  238.             return null;  
  239.         }  
  240.   
  241.     }  
  242.   
  243.     public static String lastname(String name) {  
  244.         String[] ls = name.split("\\.");  
  245.   
  246.         return ls[ls.length - 1];  
  247.     }  
  248.   
  249.     public static String getUUID() {  
  250.   
  251.         return UUID.randomUUID().toString().replaceAll("-""");  
  252.     }  
  253. }  

 第四步:Action中调用工具中的图片压缩功能

 

 

属性:

 

Java代码  收藏代码
  1.        // 图片文件上传  
  2. private File[] image;  
  3. private String[] imageFileName;  
  4. private String[] imageContentType;  

 并提供get set

 

 

具体调用:

Java代码  收藏代码
  1.  Nursetb nursetb = new Nursetb();  
  2. // 根据服务器的文件保存地址找到项目部署的绝对地址  
  3. String webPath = ServletActionContext.getServletContext().getRealPath("/");  
  4. System.out.println(webPath);  
  5. String filePath = "upload/nurimage/"  
  6.         + new SimpleDateFormat("yyyyMMdd").format(new Date()) + "/";  
  7.         
  8. String names[] = null;  
  9. if(null != this.getImage() && this.getImage()[0].length() > 0){  
  10.      names = ImageUtil.uploadImages(this.getImage()[0],   
  11.                    this.getImageFileName()[0], webPath, filePath);  
  12.        
  13. }  
  14. String imgurl = null;  
  15. if(null!=names){  
  16.     imgurl = request.getContextPath()+names[1];  
  17.       
  18.     nursetb.setImgurl(imgurl);  
  19. }  
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics