码迷,mamicode.com
首页 > 编程语言 > 详细

JAVA实现图片裁剪

时间:2015-07-03 19:00:02      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:

技术分享
 1 /**
 2      * 裁剪图片
 3      * @param src 源图片
 4      * @param dest 裁剪后的图片
 5      * @param x    裁剪范围的X坐标
 6      * @param y 裁剪范围的Y坐标
 7      * @param w 裁剪范围的高度
 8      * @param h 裁剪范围的宽度
 9      * @param destW 裁剪后图片的宽度
10      * @param destH 裁剪后图片的高度
11      * @throws IOException
12      */
13     public static void cutImage(String src, String dest, int x, int y, int w,
14             int h,int destW,int destH) throws IOException {
15         try{
16             
17             //未知问题,不知道为啥路径的最后会有\r\n
18             
19             src = src.replace("\r\n", "");
20             dest = dest.replace("\r\n", "");
21             System.out.println("CutImage:src=" + src + ";dest=" + dest + ";x=" + x + ";y=" + y);
22             File file = new File(src);
23             if(file.exists()){
24                 Iterator<ImageReader> iterator = ImageIO.getImageReadersByFormatName("jpg");
25                 ImageReader reader = (ImageReader) iterator.next();
26                 InputStream in = new FileInputStream(src);
27                 ImageInputStream iis = ImageIO.createImageInputStream(in);
28                 reader.setInput(iis, true);
29                 ImageReadParam param = reader.getDefaultReadParam();
30                 Rectangle rect = new Rectangle(x, y, w, h);
31                 param.setSourceRegion(rect);
32                 BufferedImage bi = reader.read(0, param);
33                 if(w != destW){ //被拉伸或者缩小过
34                     bi.flush();
35                     BufferedImage newImage = new BufferedImage(destW,destH,bi.getType());
36                     Graphics g = newImage.getGraphics();
37                     g.drawImage(bi,0,0,destW,destH,null,null);
38                     g.dispose();
39                     ImageIO.write(newImage, "jpg", new File(dest));
40                 }else{
41                     ImageIO.write(bi, "jpg", new File(dest));
42                 }
43                 iis.close();
44                 in.close();
45                 //最后删除临时文件
46                 file.delete();
47             }else{
48                 System.out.println("找不到要裁剪的文件:FileName=" + src);
49             }
50         }catch(Exception ex){
51             ex.printStackTrace();
52         }
53     }
cutImage

 

JAVA实现图片裁剪

标签:

原文地址:http://www.cnblogs.com/disappearwind/p/4619330.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!