日期:2014-05-17 浏览次数:20762 次
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
public class ImageCut {
/**
* 图片切割
*
* @param imagePath
* 原图地址
* @param x
* 目标切片坐标 X轴起点
* @param y
* 目标切片坐标 Y轴起点
* @param w
* 目标切片 宽度
* @param h
* 目标切片 高度
*/
public static void cut(int x1, int y1, int width, int height,String sourcePath) {
FileInputStream is = null;
ImageInputStream iis = null;
try {
is = new FileInputStream(sourcePath.trim());
String fileSuffix = sourcePath.substring(sourcePath.trim()
.lastIndexOf(".")+1);
Iterator<ImageReader> it = ImageIO
.getImageReadersByFormatName(fileSuffix.trim());
ImageReader reader = it.next();
iis = ImageIO.createImageInputStream(is);
reader.setInput(iis, true);
ImageReadParam param = reader.getDefaultReadParam();
Rectangle rect = new Rectangle(x1, y1, width, height);
param.setSourceRegion(rect);
BufferedImage bi = reader.read(0, param);
ImageIO.write(bi,fileSuffix.trim(),new File("d:123.jpg"));
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
is = null;
}
if (iis != null) {
try {
iis.close();
} catch (IOException e) {
e.printStackTrace();
}
iis = null;
}
}
}
}
//裁剪图片
ImageCut imageCut = new ImageCut();
imageCut.cut(x1, y1,x2, y2, realPath);