ITeye博客

JAVA截图

sam_kee · 2011-08-26 14:56 · JAVA截图 · 编程语言 · Markdown

截取一个图片的中央部分


package com.samkee.util;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.imageio.ImageIO;
/**
 * 截取一个图片的中央
 * @author pengchengji
 */
public class ImageUtil {
	/**
	 * 截取一个图像的中央区域
	 * @param image 图像File
	 * @param w 需要截图的宽度
	 * @param h 需要截图的高度
	 * @return 返回一个
	 * @throws IOException
	 */
	public static void cutImage(File image, int w, int h) throws IOException {
		
		// 判断参数是否合法
		if (null == image || 0 == w || 0 == h) {
			new Exception ("哎呀,截图出错!!!");
		}
		InputStream inputStream = new FileInputStream(image);
		// 用ImageIO读取字节流
		BufferedImage bufferedImage = ImageIO.read(inputStream);
		BufferedImage distin = null;
		// 返回源图片的宽度。
		int srcW = bufferedImage.getWidth();
		// 返回源图片的高度。
		int srcH = bufferedImage.getHeight();
		int x = 0, y = 0;
		// 使截图区域居中
		x = srcW / 2 - w / 2;
		y = srcH / 2 - h / 2;
		srcW = srcW / 2 + w / 2;
		srcH = srcH / 2 + h / 2;
		// 生成图片
		distin = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
		Graphics g = distin.getGraphics();
		g.drawImage(bufferedImage, 0, 0, w, h, x, y, srcW, srcH, null);
		ImageIO.write(distin, "jpg", new File("D:\\pic\\33.jpg"));
	}

	public static void main(String[] args) throws Exception {
		File file = new File("D:\\pic\\22.jpg");
		cutImage(file, 200, 200);
	}
}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。