import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.image.CropImageFilter;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class qqq {
private String cutImage(File imagePath, int x, int y, int w, int h, int width, int height) throws IOException {
Image img;
ImageFilter cropFilter;
// 读取源图像
BufferedImage bi = ImageIO.read(imagePath);
int srcWidth = bi.getWidth(); // 源图宽度
int srcHeight = bi.getHeight(); // 源图高度
// 若原图大小大于切片大小,设置目标图片大小
if (w > srcWidth) {
w = srcWidth;
}
if (h > srcHeight) {
h = srcHeight;
}
// 进行切割
if (srcWidth >= w && srcHeight >= h) {
Image image = bi.getScaledInstance(srcWidth, srcHeight, Image.SCALE_DEFAULT);
cropFilter = new CropImageFilter(x, y, w, h);
img = Toolkit.getDefaultToolkit().createImage(new FilteredImageSource(image.getSource(), cropFilter));
BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = tag.getGraphics();
g.drawImage(img, 0, 0, width, height, null); // 绘制缩小后的图
g.dispose();
// 获取源文件路径
String path = imagePath.getPath();
// 拼接新的输出文件的路径
String[] split = path.split("\\.");
String newPath = split[0] + "_cut." + split[1];
// 创建文件
File wj = new File(newPath);
// 输出为文件
ImageIO.write(tag, "PNG", wj);
return newPath;
}
return null;
}
}
java 图片裁剪
猜你喜欢
转载自blog.csdn.net/qq_14861089/article/details/54601959
今日推荐
周排行