1 /**
 2      * 根据传入的图片坐标进行图片截取
 3      * 
 4      * @param x  X起点坐标
 5      * @param x2 Y终点坐标
 6      * @param scaleWidth  宽度
 7      * @param scaleHeight 高度
 8      * @param originPath 原始图片的存放路径
 9      * @param savePath 截取后图片的存储路径
10      * @throws IOException
11      */
12     public static void scissor(int x, int y, int scaleWidth, int scaleHeight,
13             String originPath, String savePath) throws IOException {
14         
15         FileInputStream is = null;
16         ImageInputStream iis = null;
17 
18         try {
19             
20             // 读取图片文件
21             is = new FileInputStream(originPath);
22 
23             /*
24              * 返回包含所有当前已注册 ImageReader 的 Iterator,
25              * 这些 ImageReader 声称能够解码指定格式。
26              * 参数:formatName - 包含非正式格式名称 .(例如 "jpeg" 或 "tiff")等 。
27              */
28             Iterator<ImageReader> it = ImageIO
29                     .getImageReadersByFormatName(getExtention(originPath)
30                             .toLowerCase());
31             ImageReader reader = it.next();
32             // 获取图片流
33             iis = ImageIO.createImageInputStream(is);
34 
35             /*
36              * iis:读取源.true:只向前搜索,将它标记为 ‘只向前搜索’。
37              * 此设置意味着包含在输入源中的图像将只按顺序读取,可能允许 
38              * reader 避免缓存包含与以前已经读取的图像关联的数据的那些输入部分。
39              */
40             reader.setInput(iis, true);
41 
42             /*
43              * 描述如何对流进行解码的类,用于指定如何在输入时从 Java Image I/O
44              * 框架的上下文中的流转换一幅图像或一组图像。用于特定图像格式的插件 
45              * 将从其 ImageReader 实现的
46              * getDefaultReadParam方法中返回 ImageReadParam 的实例。
47              */
48             ImageReadParam param = reader.getDefaultReadParam();
49 
50             /*
51              * 图片裁剪区域。Rectangle 指定了坐标空间中的一个区域,通过 Rectangle 对象
52              * 的左上顶点的坐标(x,y)、宽度和高度可以定义这个区域。
53              */
54             Rectangle rect = new Rectangle(x, y, scaleWidth, scaleHeight);
55 
56             // 提供一个 BufferedImage,将其用作解码像素数据的目标。
57             param.setSourceRegion(rect);
58 
59             /*
60              * 使用所提供的 ImageReadParam 读取通过索引 imageIndex 指定的对象,并将 它作为一个完整的
61              * BufferedImage 返回。
62              */
63             BufferedImage bi = reader.read(0, param);
64 
65             // 保存新图片
66             ImageIO.write(bi, getExtention(originPath).toLowerCase(), new File(
67                     savePath));
68         } finally {
69             if (is != null)
70                 is.close();
71             if (iis != null)
72                 iis.close();
73         }
74     }

 

posted on 2012-11-02 11:46  NeverGiveUp_ZONE  阅读(432)  评论(0编辑  收藏  举报