Java图片剪裁功能实现

5 篇文章 0 订阅
http://shensy.iteye.com/blog/1621651

目前一些社交型互联网应用都有一些上传图片(例如头像,照片等)对预览图进行剪裁的功能。前一段时间在工作也遇到这个问题,总结一下基本实现步骤及代码(包含图片放大,缩小,设置品质,对指定点区域剪裁功能),使用JPEG格式图片测试通过,其它格式图片尚未验证。
一、基本步骤:
1.将图片文件的InputStream转换为ImageReader,并从ImageReader中读取BufferedImage信息.
2.然后使用javax.image包以及Java image scaling开源项目对图片进行缩放.
3.使用java.awt.image类对java.awt.BufferedImage进行剪裁.
4.最后写入文件,如果是JPG图片可以设置图片品质(压缩比)即JPEGEncodeParam.setQuality.
二、程序相关:
Java代码
/**
* 剪裁图片.
*
* @param file 要剪裁的图片
* @param scale 放大缩小比率
* @param cropX x轴起点坐标
* @param cropY y轴起点坐标
* @param targetWidth 目标图片的长
* @param targetHeight 目标图片的宽
*/
public static File crop(File file, Double scale, int cropX, int cropY, int targetWidth, int targetHeight) throws IOException {
BufferedImage source;
String format;
InputStream is = null;
try {
is = new FileInputStream(file);

// 从InputStream中读取图片流信息
ImageInputStream iis = ImageIO.createImageInputStream(is);
Iterator iter = ImageIO.getImageReaders(iis);
if (!iter.hasNext()) {
return null;
}
ImageReader reader = (ImageReader) iter.next();
ImageReadParam param = reader.getDefaultReadParam();
reader.setInput(iis, true, true);
try {
source = reader.read(0, param);
format = reader.getFormatName();
} finally {
reader.dispose();
iis.close();
}
} finally {
IOUtils.closeQuietly(is);
}

//调整放大缩小比率
int width = Double.valueOf(scale * source.getWidth()).intValue();
int height = Double.valueOf(scale * source.getHeight()).intValue();
BufferedImage scaled = scale(source, width, height);

//剪裁图片
ImageFilter filter = new CropImageFilter(cropX, cropY, targetWidth, targetHeight);
Image cropped = Toolkit.getDefaultToolkit().createImage(new FilteredImageSource(scaled.getSource(), filter));

//渲染新图片
BufferedImage image = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
g.drawImage(cropped, 0, 0, null);
g.dispose();

//写入文件
return writeToTempFile(image, format);
}
其中用到了Java image scaling开源工具,对图片进行缩放。
Java代码
/**
* 放大缩小图片到指定宽和高
*
* @param image Image to scale
* @param width Width of image
* @param height Height of image
* @return Scaled image file
*/
public static BufferedImage scale(BufferedImage image, int width, int height) {
ResampleOp resampleOp = new ResampleOp(width, height);
resampleOp.setUnsharpenMask(AdvancedResizeOp.UnsharpenMask.Normal);
return resampleOp.filter(image, null);
}
最后写入临时文件:
Java代码
/**
* 将图片写入临时文件
*/
public static File writeToTempFile(BufferedImage image, Format type) {
if (Format.JPEG != type) {
return writeToTempFileWithoutCompress(image, type);
} else {
try {
return compress(image, JPG_DEFAULT_QUALITY);
} catch (IOException e) {
return writeToTempFileWithoutCompress(image, type);
}
}
}
不是JPEG格式不压缩:
Java代码
/**
* 不压缩将图片写入文件
*/
public static File writeToTempFileWithoutCompress(BufferedImage image, Format type) {
File destination = generateTempFile(type);
try {
ImageIO.write(image, type.toString(), destination);
} catch (IOException e) {
throw new RuntimeException(e);
}
return destination;
}

/**
* 压缩图片到指定的压缩比率
*/
public static File compress(BufferedImage image, float quality) throws IOException {
// Build param
JPEGEncodeParam param = null;
try {
param = JPEGCodec.getDefaultJPEGEncodeParam(image);
param.setQuality(quality, false);
} catch (RuntimeException e) {
// Ignore
param = null;
}

// Build encoder
File destination = generateTempFile(Format.JPEG);
FileOutputStream os = null;
try {
os = FileUtils.openOutputStream(destination);
JPEGImageEncoder encoder;
if (param != null) {
encoder = JPEGCodec.createJPEGEncoder(os, param);
} else {
encoder = JPEGCodec.createJPEGEncoder(os);
}
encoder.encode(image);
} finally {
IOUtils.closeQuietly(os);
}
return destination;
}
其中还用到了Apache的commons-io工具集。

测试时发现设置0.9以上的压缩比后会使有些JPG图片的大小不减小反而比原图更大了,具体原因还不太清楚。
希望对看到的人有所帮助。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值