java图片文件处理工具类【包括图片缩放,剪切等功能】

  1. import java.awt.Graphics;  
  2. import java.awt.GraphicsConfiguration;  
  3. import java.awt.GraphicsDevice;  
  4. import java.awt.GraphicsEnvironment;  
  5. import java.awt.HeadlessException;  
  6. import java.awt.Image;  
  7. import java.awt.Rectangle;  
  8. import java.awt.Transparency;  
  9. import java.awt.image.BufferedImage;  
  10. import java.io.File;  
  11. import java.io.FileInputStream;  
  12. import java.io.FileOutputStream;  
  13. import java.io.IOException;  
  14. import java.text.SimpleDateFormat;  
  15. import java.util.Date;  
  16. import java.util.Iterator;  
  17. import java.util.Random;  
  18.   
  19. import javax.imageio.ImageIO;  
  20. import javax.imageio.ImageReadParam;  
  21. import javax.imageio.ImageReader;  
  22. import javax.imageio.stream.ImageInputStream;  
  23. import javax.swing.ImageIcon;  
  24.   
  25. import com.sun.image.codec.jpeg.JPEGCodec;  
  26. import com.sun.image.codec.jpeg.JPEGImageEncoder;  
  27.   
  28. /** 
  29.  * @作者 王建明 
  30.  * @创建日期 2012-6-16 
  31.  * @创建时间 下午02:35:31 
  32.  * @版本号 V 1.0 
  33.  */  
  34. public class IconCompressUtil {  
  35.     public String path = "";  
  36.   
  37.     public IconCompressUtil(String path) {  
  38.         this.path = path;  
  39.     }  
  40.   
  41.     public void change(int size) {  
  42.         compressImg(new File(path), size, null);  
  43.     }  
  44.   
  45.     /** 
  46.      * @param oldfile 
  47.      * @param size 
  48.      * @param newfile 
  49.      * @return 
  50.      * @作者 王建明 
  51.      * @创建日期 2012-6-16 
  52.      * @创建时间 下午03:30:48 
  53.      * @描述 —— 将oldfile的图片文件等比例压缩为size的newfile文件 
  54.      */  
  55.     public static File compressImg(File oldfile, int size, File newfile) {  
  56.         if(!newfile.exists())  
  57.             try {  
  58.                 newfile.createNewFile();  
  59.             } catch (IOException e1) {  
  60.                 // TODO Auto-generated catch block  
  61.                 //e1.printStackTrace();  
  62.                 System.out.println("无法创建文件!!!");  
  63.                 return null;  
  64.             }  
  65.         BufferedImage bi;  
  66.         try {  
  67.             System.out.println("正在压缩:" + oldfile.getName());  
  68.             bi = ImageIO.read(new FileInputStream(oldfile));  
  69.             int width = bi.getWidth();  
  70.             int height = bi.getHeight();  
  71.             if (width > size || height > size) {  
  72.                 Image image;  
  73.                 if (width > height) {  
  74.                     height = (int) (bi.getHeight() / (bi.getWidth() * 1d) * size);  
  75.                     image = bi.getScaledInstance(size, height,  
  76.                             Image.SCALE_DEFAULT);  
  77.                 } else {  
  78.                     width = (int) (bi.getWidth() / (bi.getHeight() * 1d) * size);  
  79.                     image = bi.getScaledInstance(width, size,  
  80.                             Image.SCALE_DEFAULT);  
  81.                 }  
  82.                 ImageIO.write(toBufferedImage(image), "png",  
  83.                         new FileOutputStream(newfile));  
  84.                 System.out.println("压缩完成:" + newfile.getName());  
  85.                 return newfile;  
  86.             } else {  
  87.                 System.out.println("无须压缩:" + oldfile.getName());  
  88.                 return oldfile;  
  89.             }  
  90.         } catch (Exception e) {  
  91.             e.printStackTrace();  
  92.         }  
  93.         return null;  
  94.     }  
  95.   
  96.     public static BufferedImage toBufferedImage(Image image) {  
  97.         if (image instanceof BufferedImage) {  
  98.             return (BufferedImage) image;  
  99.         }  
  100.         image = new ImageIcon(image).getImage();  
  101.         BufferedImage bimage = null;  
  102.         GraphicsEnvironment ge = GraphicsEnvironment  
  103.                 .getLocalGraphicsEnvironment();  
  104.         try {  
  105.             int transparency = Transparency.TRANSLUCENT;  
  106.             GraphicsDevice gs = ge.getDefaultScreenDevice();  
  107.             GraphicsConfiguration gc = gs.getDefaultConfiguration();  
  108.             bimage = gc.createCompatibleImage(image.getWidth(null), image  
  109.                     .getHeight(null), transparency);  
  110.         } catch (HeadlessException e) {  
  111.         }  
  112.         if (bimage == null) {  
  113.             int type = BufferedImage.TYPE_INT_RGB;  
  114.             bimage = new BufferedImage(image.getWidth(null), image  
  115.                     .getHeight(null), type);  
  116.         }  
  117.         Graphics g = bimage.createGraphics();  
  118.         g.drawImage(image, 00null);  
  119.         g.dispose();  
  120.         return bimage;  
  121.     }  
  122.   
  123.     /** 
  124.      * @return 
  125.      * @作者 王建明 
  126.      * @创建日期 2012-8-2 
  127.      * @创建时间 下午02:00:41 
  128.      * @描述 —— 生成随机名字,不可能重复(用于文件的命名) 
  129.      */  
  130.     public static String getRandomName() {  
  131.         Random r = new Random();  
  132.         SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmssSSS");  
  133.         StringBuffer sb = new StringBuffer();  
  134.         sb.append(r.nextInt(100));  
  135.         sb.append(r.nextInt(100));  
  136.         sb.append("_");  
  137.         sb.append(sdf.format(new Date()));  
  138.         sb.append("_");  
  139.         sb.append(r.nextInt(100));  
  140.         sb.append(r.nextInt(100));  
  141.         return sb.toString();  
  142.     }  
  143.   
  144.     /** 
  145.      * @param inputFile源文件 
  146.      * @param outFile生成文件 
  147.      * @param width指定宽度 
  148.      * @param height指定高度 
  149.      * @param proportion是否等比例操作 
  150.      * @return 
  151.      * @作者 王建明 
  152.      * @创建日期 2012-8-2 
  153.      * @创建时间 下午02:02:38 
  154.      * @描述 —— 是否等比例缩放图片 
  155.      */  
  156.     public static boolean compressPic(String inputFile, String outFile,  
  157.             int width, int height, boolean proportion) {  
  158.         try {  
  159.             // 获得源文件  
  160.             File file = new File(inputFile);  
  161.             if (!file.exists()) {  
  162.                 return false;  
  163.             }  
  164.             Image img = ImageIO.read(file);  
  165.             // 判断图片格式是否正确  
  166.             if (img.getWidth(null) == -1) {  
  167.                 return false;  
  168.             } else {  
  169.                 int newWidth;  
  170.                 int newHeight;  
  171.                 // 判断是否是等比缩放  
  172.                 if (proportion == true) {  
  173.                     // 为等比缩放计算输出的图片宽度及高度  
  174.                     double rate1 = ((double) img.getWidth(null))  
  175.                             / (double) width + 0.1;  
  176.                     double rate2 = ((double) img.getHeight(null))  
  177.                             / (double) height + 0.1;  
  178.                     // 根据缩放比率大的进行缩放控制  
  179.                     double rate = rate1 > rate2 ? rate1 : rate2;  
  180.                     newWidth = (int) (((double) img.getWidth(null)) / rate);  
  181.                     newHeight = (int) (((double) img.getHeight(null)) / rate);  
  182.                 } else {  
  183.                     newWidth = width; // 输出的图片宽度  
  184.                     newHeight = height; // 输出的图片高度  
  185.                 }  
  186.   
  187.                 // 如果图片小于目标图片的宽和高则不进行转换  
  188.                 /* 
  189.                  * if (img.getWidth(null) < width && img.getHeight(null) < 
  190.                  * height) { newWidth = img.getWidth(null); newHeight = 
  191.                  * img.getHeight(null); } 
  192.                  */  
  193.                 BufferedImage tag = new BufferedImage((int) newWidth,  
  194.                         (int) newHeight, BufferedImage.TYPE_INT_RGB);  
  195.   
  196.                 // Image.SCALE_SMOOTH 的缩略算法 生成缩略图片的平滑度的,优先级比速度高 生成的图片质量比较好 但速度慢  
  197.                 tag.getGraphics().drawImage(  
  198.                         img.getScaledInstance(newWidth, newHeight,  
  199.                                 Image.SCALE_SMOOTH), 00null);  
  200.                 FileOutputStream out = new FileOutputStream(outFile);  
  201.                 // JPEGImageEncoder可适用于其他图片类型的转换  
  202.                 JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);  
  203.                 encoder.encode(tag);  
  204.                 out.close();  
  205.             }  
  206.         } catch (IOException ex) {  
  207.             ex.printStackTrace();  
  208.         }  
  209.         return true;  
  210.     }  
  211.   
  212.     /** 
  213.      * @param srcFile源文件 
  214.      * @param outFile输出文件 
  215.      * @param x坐标 
  216.      * @param y坐标 
  217.      * @param width宽度 
  218.      * @param height高度 
  219.      * @return 
  220.      * @作者 王建明 
  221.      * @创建日期 2012-8-2 
  222.      * @创建时间 下午02:05:03 
  223.      * @描述 —— 裁剪图片 
  224.      */  
  225.     public static boolean cutPic(String srcFile, String outFile, int x, int y,  
  226.             int width, int height) {  
  227.         FileInputStream is = null;  
  228.         ImageInputStream iis = null;  
  229.         try {  
  230.             // 如果源图片不存在  
  231.             if (!new File(srcFile).exists()) {  
  232.                 return false;  
  233.             }  
  234.   
  235.             // 读取图片文件  
  236.             is = new FileInputStream(srcFile);  
  237.   
  238.             // 获取文件格式  
  239.             String ext = srcFile.substring(srcFile.lastIndexOf(".") + 1);  
  240.   
  241.             // ImageReader声称能够解码指定格式  
  242.             Iterator<ImageReader> it = ImageIO.getImageReadersByFormatName(ext);  
  243.             ImageReader reader = it.next();  
  244.   
  245.             // 获取图片流  
  246.             iis = ImageIO.createImageInputStream(is);  
  247.   
  248.             // 输入源中的图像将只按顺序读取  
  249.             reader.setInput(iis, true);  
  250.   
  251.             // 描述如何对流进行解码  
  252.             ImageReadParam param = reader.getDefaultReadParam();  
  253.   
  254.             // 图片裁剪区域  
  255.             Rectangle rect = new Rectangle(x, y, width, height);  
  256.   
  257.             // 提供一个 BufferedImage,将其用作解码像素数据的目标  
  258.             param.setSourceRegion(rect);  
  259.   
  260.             // 使用所提供的 ImageReadParam 读取通过索引 imageIndex 指定的对象  
  261.             BufferedImage bi = reader.read(0, param);  
  262.   
  263.             // 保存新图片  
  264.             File tempOutFile = new File(outFile);  
  265.             if (!tempOutFile.exists()) {  
  266.                 tempOutFile.mkdirs();  
  267.             }  
  268.             ImageIO.write(bi, ext, new File(outFile));  
  269.             return true;  
  270.         } catch (Exception e) {  
  271.             e.printStackTrace();  
  272.             return false;  
  273.         } finally {  
  274.             try {  
  275.                 if (is != null) {  
  276.                     is.close();  
  277.                 }  
  278.                 if (iis != null) {  
  279.                     iis.close();  
  280.                 }  
  281.             } catch (IOException e) {  
  282.                 e.printStackTrace();  
  283.                 return false;  
  284.             }  
  285.         }  
  286.     }  
  287.   
  288.     /** 
  289.      * @param doubleValue 
  290.      * @return 
  291.      * @作者 王建明 
  292.      * @创建日期 2012-8-6 
  293.      * @创建时间 下午05:24:15 
  294.      * @描述 —— 将浮点型数据保留整数位转换成int型 
  295.      */  
  296.     public static Integer getRoundIntFromDouble(Double doubleValue) {  
  297.         return Integer.parseInt(String.valueOf(Math.round(doubleValue)));  
  298.     }  

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值