public static void cutImage(InputStream input, OutputStream out,String type, int x, int y, int width, int height)throws IOException {
ImageInputStream imageStream = null;
try {
String imageType = (null == type || "".equals(type)) ? "jpg" : type;Iterator readers = ImageIO
.getImageReadersByFormatName(imageType);
ImageReader reader = readers.next();
imageStream = ImageIO.createImageInputStream(input);
reader.setInput(imageStream, true);
ImageReadParam param = reader.getDefaultReadParam();
Rectangle rect = new Rectangle(x, y, width, height);
param.setSourceRegion(rect);
BufferedImage bi = reader.read(0, param);
ImageIO.write(bi, imageType, out);
} finally {
imageStream.close();
input.close();
out.close();
}
}
使用示例:
//locUrl为大图路径
String[] targetRect=info.getTargetRect().split("/");
//小图保存本地
ImageUtils.cutImage(new FileInputStream(locUrl),new FileOutputStream(smallLoc),"jpg", Integer.parseInt(targetRect[0]),
Integer.parseInt(targetRect[1]), Integer.parseInt(targetRect[2]), Integer.parseInt(targetRect[3]));
网友评论