概述:
基于Sun自带lib进行图片的操作,此处主要展示图片的缩放和图片剪裁
实现:
图片缩放:
/**
* 图片伸缩,不破坏图片
*
* @param srcFile 原图片路径
* @param dstFile 目标图片路径
* @param dstWidth 目标宽度
* @param dstHeight 目标高度
* @date 2013-11-1
*/
public static void scale(String srcFile, String dstFile, int dstWidth, int dstHeight) {
try {
ImageInputStream iis = ImageIO.createImageInputStream(new File(srcFile));
Iterator<ImageReader> iterator = ImageIO.getImageReaders(iis);
ImageReader reader = (ImageReader) iterator.next();
reader.setInput(iis, true);
BufferedImage source = reader.read(0);
BufferedImage tag = new BufferedImage(dstWidth, dstHeight, source.getType());
tag.getGraphics().drawImage(source, 0, 0, dstWidth, dstHeight, null);
File file = new File(dstFile);
ImageIO.write(tag, reader.getFormatName(), file);
} catch (Exception e) {
e.printStackTrace();
}
}
图片剪裁:
/**
* 图片剪裁,基于起始坐标(x,y)和范围[widthRange,heightRange]
*
* @param srcFile 原图片路径
* @param dstFile 目标图片路径
* @param x 起始X
* @param y 起始Y
* @param widthRange 范围width
* @param heightRange 范围height
* @date 2013-11-1
*/
public static void cut(String srcFile, String dstFile, int x, int y, int widthRange,
int heightRange) {
try {
ImageInputStream iis = ImageIO.createImageInputStream(new File(srcFile));
Iterator<ImageReader> iterator = ImageIO.getImageReaders(iis);
ImageReader reader = (ImageReader) iterator.next();
reader.setInput(iis, true);
ImageReadParam param = reader.getDefaultReadParam();
Rectangle rectangle = new Rectangle(x, y, widthRange, heightRange);
param.setSourceRegion(rectangle);
BufferedImage bi = reader.read(0, param);
File file = new File(dstFile);
ImageIO.write(bi, reader.getFormatName(), file);
} catch (Exception e) {
e.printStackTrace();
}
}
测试:
public static void main(String[] args) {
String srcFile = "G:/1.jpg";
String dstFile = "G:/test.jpg";
int width = 120;
int height = 12000;
cut(srcFile, dstFile, 10, 10, width, height);
scale(srcFile, dstFile, width, height);
}
评价:
效率很低