JDK类库裁剪图片
工具代码
/**
* 裁剪原图,生成新的图片
* @param srcPath 原图地址
* @param destPath 裁剪后的图片地址
* @param x 裁剪开始x坐标
* @param y 裁剪开始y坐标
* @param width 裁剪宽度
* @param height 裁剪高度
* @param formatName 图片类型
*/
public static boolean cutImage(String srcPath, String destPath, int x, int y, int width, int height, String formatName) {
boolean cutSuccess = false;
Iterator<ImageReader> ite = ImageIO.getImageReadersByFormatName(formatName);
if (ite.hasNext()) {
ImageReader reader = ite.next();
InputStream is = null;
try {
is = new FileInputStream(srcPath);
ImageInputStream iis = ImageIO.createImageInputStream(is);
reader.setInput(iis);
ImageReadParam defaultReadParam = reader.getDefaultReadParam();
Rectangle rec = new Rectangle(x, y, width, height);
defaultReadParam.setSourceRegion(rec);
BufferedImage bi = reader.read(0, defaultReadParam);
cutSuccess = ImageIO.write(bi, formatName, new File(destPath));
} catch (IOException e) {
System.out.println("cut image["+srcPath+"] failed");
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} else {
throw new RuntimeException("不支持的格式["+ formatName +"]");
}
return cutSuccess;
}
测试代码
/**
* 测试图片剪切
*/
@Test
public void testCutImage() {
String imageName = "simple.jpg";
String cutImageName = "simple_cut.jpg";
String srcPath = IMAGE_PATH + imageName;
String destPath = IMAGE_PATH + cutImageName;
int x = 10;
int y = 40;
int width = 180;
int height = 120;
String formatName = "jpg";
ImageUtil.cutImage(srcPath, destPath, x, y, width, height, formatName);
}
原图
新图
完整源码:https://github.com/ConstXiong/xtools
【Java面试题与答案】整理推荐