package com.yunmall.framework.core.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;
import com.yunmall.framework.core.log.LogTrace;
/**
* 裁剪图片
*
* @version 1.0
* @createDate 2012-8-10
* @modifyDate 2012-8-14
*/
public class ImageOperate {
private static final LogTrace log = new LogTrace("ImageOperate");
/**
* 按指定坐标剪切图片并生成新图片
*
* @param image
* 图片源文件
* @param formatName
* 图片格式,如gif,jpg
* @param targetFile
* 新图片
* @param x
* 指定剪切坐标点的X坐标
* @param y
* 指定剪切坐标点的y坐标
* @param width
* 指定剪切宽度
* @param height
* 指定剪切高度
* @return 剪切后的新图片
* @throws IOException
* IO异常
*/
public static File cutImage(File image, String formatName, File targetFile, int x, int y,
int width, int height) throws IOException {
BufferedImage bi = cutImage(image, formatName, x, y, width, height);
ImageIO.write(bi, "jpg", targetFile); // 保存新图片
return targetFile;
}
/**
* 按指定坐标剪切图片
*
* @param image
* 图片源文件
* @param formatName
* 图片格式,如gif,jpg
* @param x
* 指定剪切坐标点的X坐标
* @param y
* 指定剪切坐标点的y坐标
* @param width
* 指定剪切宽度
* @param height
* 指定剪切高度
* @return 剪切后的图片流
* @throws IOException
* IO异常
*/
public static BufferedImage cutImage(File image, String formatName, int x, int y, int width,
int height) throws IOException {
FileInputStream is = null;
ImageInputStream iis = null;
BufferedImage bi = null;
try {
is = new FileInputStream(image);
Iterator<ImageReader> it = ImageIO.getImageReadersByFormatName(formatName);
ImageReader reader = it.next();
iis = ImageIO.createImageInputStream(is); // 获取图片流
reader.setInput(iis, true);
ImageReadParam param = reader.getDefaultReadParam();
Rectangle rect = new Rectangle(x, y, width, height); // 图片裁剪区域
param.setSourceRegion(rect); // 解码像素数据的目标。
bi = reader.read(0, param);
} catch (IOException e) {
log.error(e.getMessage());
} finally {
if (is != null) {
is.close();
}
if (iis != null) {
iis.close();
}
}
return bi;
}
}
裁剪图片
最新推荐文章于 2024-04-14 12:13:08 发布