package com.wlf.content.util;
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;
/**
* 图片出来工具类
*
* @author 陈宗勇 (czy.keith@qq.com)
*
*/
public class ImageUtil {
/**
* 剪切图片
*
* @param srcFile
* 图片源地址
* @param destFile
* 图片要保存的地址
* @param x
* x坐标
* @param y
* y坐标
* @param width
* 图片要截取的宽
* @param height
* 图片要截取的高
*/
public static void cutImage(String srcFile, String destFile, int x, int y,
int width, int height) {
FileInputStream fis = null;
ImageInputStream iis = null;
try {
//读取图片的文件流
fis = new FileInputStream(srcFile);
//得到文件的后缀名
String endName = srcFile.substring(srcFile.lastIndexOf(".") + 1);
Iterator<ImageReader> it = ImageIO
.getImageReadersByFormatName(endName);
ImageReader reader = it.next();
iis = ImageIO.createImageInputStream(fis);
reader.setInput(iis, true);
ImageReadParam irp = reader.getDefaultReadParam();
Rectangle rect = new Rectangle(x, y, width, height);
irp.setSourceRegion(rect);
BufferedImage bImage = reader.read(0, irp);
// 保存图片
ImageIO.write(bImage, endName, new File(destFile));
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (iis != null) {
try {
iis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
cutImage("f:/6.jpg", "f:/5.jpg", 50, 50, 400, 400);
}
}