Java图片压缩并上传

  1. public void uploadFile(@RequestParam(value = "file", required = false)MultipartFile[] file,HttpServletRequest request, HttpServletResponse response) throws IOException {     
  2.         //附件上传  
  3.         for (MultipartFile multipartFile : file) {  
  4.             //获取文件名  
  5.             String fileName = multipartFile.getOriginalFilename();  
  6.             if(null!=fileName && !"".equals(fileName)){  
  7.                 try {  
  8.                     String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();//文件扩展名  
  9.                     String newfilename = StringUtil.getUUID() + "." + fileExt; //生成uuid文件名  
  10.                     String savePath = "upload/images/" + newfilename;  
  11.                     File folder=new File(PropUtils.get("web.root")+"upload/images");  
  12.                     if(!folder.exists()){  
  13.                         folder.mkdirs();//如果文件夹不存在 创建文件夹  
  14.                     }  
  15.                     //上传文件  
  16. //                  multipartFile.transferTo(new File(PropUtils.get("web.root") + savePath));  
  17.                       
  18.                     //压缩文件  
  19.                     ImageHelper.compress(multipartFile.getInputStream(), new File(PropUtils.get("web.root") + savePath), 700);  
  20.                       
  21.                     //数据库保存图片路径信息  
  22.                 } catch (Exception e) {  
  23.                     e.printStackTrace();  
  24.                     return;  
  25.                 }  
  26.             }  
  27.         }  
  28.     }  
[java]  view plain  copy
  1. package com.xypt.utils;  
  2.   
  3. import java.awt.Graphics2D;  
  4. import java.awt.Rectangle;  
  5. import java.awt.RenderingHints;  
  6. import java.awt.geom.AffineTransform;  
  7. import java.awt.image.BufferedImage;  
  8. import java.awt.image.ColorModel;  
  9. import java.awt.image.WritableRaster;  
  10. import java.io.File;  
  11. import java.io.FileInputStream;  
  12. import java.io.FileNotFoundException;  
  13. import java.io.IOException;  
  14. import java.io.InputStream;  
  15.   
  16. import javax.imageio.ImageIO;  
  17.   
  18.   
  19. /** 
  20.  * 图片工具类 
  21.  * @author 
  22.  * @description 图片压缩 截取 
  23.  * 
  24.  */  
  25. public class ImageHelper {  
  26.     /** 
  27.      * 实现图像的等比缩放 
  28.      *  
  29.      * @param source 
  30.      * @param targetW 
  31.      * @param targetH 
  32.      * @return 
  33.      */  
  34.     private static BufferedImage resize(BufferedImage source, int targetW, int targetH) {  
  35.         // targetW,targetH分别表示目标长和宽  
  36.         int type = source.getType();  
  37.         BufferedImage target = null;  
  38.         double sx = (double) targetW / source.getWidth();  
  39.         double sy = (double) targetH / source.getHeight();  
  40.         // 这里想实现在targetW,targetH范围内实现等比缩放。如果不需要等比缩放  
  41.         // 则将下面的if else语句注释即可  
  42.         if (sx < sy) {  
  43.             sx = sy;  
  44.             targetW = (int) (sx * source.getWidth());  
  45.         } else {  
  46.             sy = sx;  
  47.             targetH = (int) (sy * source.getHeight());  
  48.         }  
  49.         if (type == BufferedImage.TYPE_CUSTOM) { // handmade  
  50.             ColorModel cm = source.getColorModel();  
  51.             WritableRaster raster = cm.createCompatibleWritableRaster(targetW, targetH);  
  52.             boolean alphaPremultiplied = cm.isAlphaPremultiplied();  
  53.             target = new BufferedImage(cm, raster, alphaPremultiplied, null);  
  54.         } else  
  55.             target = new BufferedImage(targetW, targetH, type);  
  56.         Graphics2D g = target.createGraphics();  
  57.         // smoother than exlax:  
  58.         g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);  
  59.         g.drawRenderedImage(source, AffineTransform.getScaleInstance(sx, sy));  
  60.         g.dispose();  
  61.         return target;  
  62.     }  
  63.   
  64.     /** 
  65.      * 实现图像的等比缩放和缩放后的截取, 处理成功返回true, 否则返回false 
  66.      *  
  67.      * @param inFilePath 
  68.      *            要截取文件的路径 
  69.      * @param outFilePath 
  70.      *            截取后输出的路径 
  71.      * @param width 
  72.      *            要截取宽度 
  73.      * @param hight 
  74.      *            要截取的高度 
  75.      * @throws Exception 
  76.      */  
  77.     public static boolean compress(String inFilePath, String outFilePath, int width, int hight) {  
  78.         boolean ret = false;  
  79.         File file = new File(inFilePath);  
  80.         File saveFile = new File(outFilePath);  
  81.         InputStream in = null;  
  82.         try {  
  83.             in = new FileInputStream(file);  
  84.             ret = compress(in, saveFile, width, hight);  
  85.         } catch (FileNotFoundException e) {  
  86.             e.printStackTrace();  
  87.             ret = false;  
  88.         } finally {  
  89.             if (null != in) {  
  90.                 try {  
  91.                     in.close();  
  92.                 } catch (IOException e) {  
  93.                     e.printStackTrace();  
  94.                 }  
  95.             }  
  96.         }  
  97.   
  98.         return ret;  
  99.     }  
  100.   
  101.     /** 
  102.      * 实现图像的等比缩放和缩放后的截取, 处理成功返回true, 否则返回false 
  103.      *  
  104.      * @param in 
  105.      *            要截取文件流 
  106.      * @param outFilePath 
  107.      *            截取后输出的路径 
  108.      * @param width 
  109.      *            要截取宽度 
  110.      * @param hight 
  111.      *            要截取的高度 
  112.      * @throws Exception 
  113.      */  
  114.     public static boolean compress(InputStream in, File saveFile, int width, int hight) {  
  115.         // boolean ret = false;  
  116.         BufferedImage srcImage = null;  
  117.         try {  
  118.             srcImage = ImageIO.read(in);  
  119.         } catch (IOException e) {  
  120.             e.printStackTrace();  
  121.             return false;  
  122.         }  
  123.   
  124.         if (width > 0 || hight > 0) {  
  125.             // 原图的大小  
  126.             int sw = srcImage.getWidth();  
  127.             int sh = srcImage.getHeight();  
  128.             // 如果原图像的大小小于要缩放的图像大小,直接将要缩放的图像复制过去  
  129.             if (sw > width && sh > hight) {  
  130.                 srcImage = resize(srcImage, width, hight);  
  131.             } else {  
  132.                 String fileName = saveFile.getName();  
  133.                 String formatName = fileName.substring(fileName.lastIndexOf('.') + 1);  
  134.                 try {  
  135.                     ImageIO.write(srcImage, formatName, saveFile);  
  136.                 } catch (IOException e) {  
  137.                     e.printStackTrace();  
  138.                     return false;  
  139.                 }  
  140.                 return true;  
  141.             }  
  142.         }  
  143.         // 缩放后的图像的宽和高  
  144.         int w = srcImage.getWidth();  
  145.         int h = srcImage.getHeight();  
  146.         // 如果缩放后的图像和要求的图像宽度一样,就对缩放的图像的高度进行截取  
  147.         if (w == width) {  
  148.             // 计算X轴坐标  
  149.             int x = 0;  
  150.             int y = h / 2 - hight / 2;  
  151.             try {  
  152.                 saveSubImage(srcImage, new Rectangle(x, y, width, hight), saveFile);  
  153.             } catch (IOException e) {  
  154.                 e.printStackTrace();  
  155.                 return false;  
  156.             }  
  157.         }  
  158.         // 否则如果是缩放后的图像的高度和要求的图像高度一样,就对缩放后的图像的宽度进行截取  
  159.         else if (h == hight) {  
  160.             // 计算X轴坐标  
  161.             int x = w / 2 - width / 2;  
  162.             int y = 0;  
  163.             try {  
  164.                 saveSubImage(srcImage, new Rectangle(x, y, width, hight), saveFile);  
  165.             } catch (IOException e) {  
  166.                 e.printStackTrace();  
  167.                 return false;  
  168.             }  
  169.         }  
  170.   
  171.         return true;  
  172.     }  
  173.   
  174.     /** 
  175.      * 实现图像的等比缩放和缩放后的截取, 处理成功返回true, 否则返回false 
  176.      *  
  177.      * @param in 
  178.      *            图片输入流 
  179.      * @param saveFile 
  180.      *            压缩后的图片输出流 
  181.      * @param proportion 
  182.      *            压缩后宽度 
  183.      * @throws Exception 
  184.      */  
  185.     public static boolean compress(InputStream in, File saveFile, float compress_width) {  
  186.         if (null == in || null == saveFile || compress_width < 1) {// 检查参数有效性  
  187.             // LoggerUtil.error(ImageHelper.class, "--invalid parameter, do  
  188.             // nothing!");  
  189.             return false;  
  190.         }  
  191.   
  192.         BufferedImage srcImage = null;  
  193.         double multiple = 1.0d;  
  194.         try {  
  195.             srcImage = ImageIO.read(in);  
  196.             int original_width = srcImage.getWidth(); // 原始宽度  
  197.             if (original_width > compress_width) {  
  198.                 multiple = original_width / compress_width; // 计算要达到指定宽度要缩放的倍数  
  199.             }  
  200.         } catch (IOException e1) {  
  201.             // TODO Auto-generated catch block  
  202.             e1.printStackTrace();  
  203.         }  
  204.   
  205.         // 原图的大小  
  206.         int width = (int) (srcImage.getWidth() / multiple);  
  207.         int hight = (int) (srcImage.getHeight() / multiple);  
  208.   
  209.         srcImage = resize(srcImage, width, hight);  
  210.   
  211.         // 缩放后的图像的宽和高  
  212.         int w = srcImage.getWidth();  
  213.         int h = srcImage.getHeight();  
  214.         // 如果缩放后的图像和要求的图像宽度一样,就对缩放的图像的高度进行截取  
  215.         if (w == width) {  
  216.             // 计算X轴坐标  
  217.             int x = 0;  
  218.             int y = h / 2 - hight / 2;  
  219.             try {  
  220.                 saveSubImage(srcImage, new Rectangle(x, y, width, hight), saveFile);  
  221.             } catch (IOException e) {  
  222.                 e.printStackTrace();  
  223.                 return false;  
  224.             }  
  225.         }  
  226.         // 否则如果是缩放后的图像的高度和要求的图像高度一样,就对缩放后的图像的宽度进行截取  
  227.         else if (h == hight) {  
  228.             // 计算X轴坐标  
  229.             int x = w / 2 - width / 2;  
  230.             int y = 0;  
  231.             try {  
  232.                 saveSubImage(srcImage, new Rectangle(x, y, width, hight), saveFile);  
  233.             } catch (IOException e) {  
  234.                 e.printStackTrace();  
  235.                 return false;  
  236.             }  
  237.         }  
  238.   
  239.         return true;  
  240.     }  
  241.   
  242.     /** 
  243.      * 实现缩放后的截图 
  244.      *  
  245.      * @param image 
  246.      *            缩放后的图像 
  247.      * @param subImageBounds 
  248.      *            要截取的子图的范围 
  249.      * @param subImageFile 
  250.      *            要保存的文件 
  251.      * @throws IOException 
  252.      */  
  253.     private static void saveSubImage(BufferedImage image, Rectangle subImageBounds, File subImageFile) throws IOException {  
  254.         if (subImageBounds.x < 0 || subImageBounds.y < 0 || subImageBounds.width - subImageBounds.x > image.getWidth() || subImageBounds.height - subImageBounds.y > image.getHeight()) {  
  255.             // LoggerUtil.error(ImageHelper.class, "Bad subimage bounds");  
  256.             return;  
  257.         }  
  258.         BufferedImage subImage = image.getSubimage(subImageBounds.x, subImageBounds.y, subImageBounds.width, subImageBounds.height);  
  259.         String fileName = subImageFile.getName();  
  260.         String formatName = fileName.substring(fileName.lastIndexOf('.') + 1);  
  261.         ImageIO.write(subImage, formatName, subImageFile);  
  262.     }  
  263.   
  264.     public static void main(String[] args) throws Exception {  
  265.   
  266.         InputStream in = null;  
  267.         // 缩放后需要保存的路径  
  268.         File saveFile = new File("d:/3_0.jpg");  
  269.   
  270.         try {  
  271.   
  272.             // 原图片的路径  
  273.             in = new FileInputStream(new File("d:/3.jpg"));  
  274.   
  275.             if (compress(in, saveFile, 700)) {  
  276.                 System.out.println("图片压缩完成!");  
  277.             }  
  278.         } catch (Exception e) {  
  279.             e.printStackTrace();  
  280.         } finally {  
  281.             in.close();  
  282.         }  
  283.     }  
  284. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值