/** * 对图片裁剪,并把裁剪完蛋新图片保存 。 * * @param srcpath: 被裁减的图片完整路径 * @param tarpath: 已裁减的新图片保存完整的路径 * @param x: 裁减矩形区域左上顶点水平位移 * @param y: 裁减矩形区域左上顶点垂直位移 * @param width: 裁减矩形区域的宽度 * @param height: 裁减矩形区域的高度 */ public static void cut(String srcpath, String tarpath, int x, int y, int width, int height) { try { // 读取图片文件 FileInputStream is = new FileInputStream(srcpath); // 获取图片流 ImageInputStream iis = ImageIO.createImageInputStream(is); // 转化成输出流 BufferedImage outputImage = getSubimage(ImageIO.read(iis), x, y, width, height); // 保存新图片 if (null != outputImage) { ImageIO.write(outputImage, "jpg", new File(tarpath)); } } catch (IOException e) { e.printStackTrace(); } } public static BufferedImage getSubimage(BufferedImage inputImage, int x, int y, int width, int height) { return getSubimage(inputImage, new Rectangle(x, y, width, height)); } public static BufferedImage getSubimage(BufferedImage inputImage, Rectangle rect) { if (rect.x < 1 || rect.y < 1 || rect.x > inputImage.getWidth() || rect.y > inputImage.getHeight()) { return null; } int x = Math.min(inputImage.getWidth(), rect.x); int y = Math.min(inputImage.getHeight(), rect.y); int width = Math.min(inputImage.getWidth() - x, rect.width); int height = Math.min(inputImage.getHeight() - y, rect.height); return inputImage.getSubimage(x, y, width, height); }
转载于:https://www.cnblogs.com/xingxiudong/archive/2010/02/23/3987038.html