压缩图片
/**
* 缩放图片(压缩图片质量,改变图片尺寸)
* 若原图宽度小于新宽度,则宽度不变!
* @param resizedFile 压缩文件
* @param originalFile 原文件
* @param maxWidth 最大宽度
* @param maxHeight 最大高度
* @param quality 图片质量参数 0.7f 相当于70%质量
*/
public static void imageResize(HttpServletRequest request, File resizedFile, File originalFile,
int maxWidth,int maxHeight, float quality) throws IOException {
if (quality > 1) {
throw new IllegalArgumentException(
"图片质量需设置在0.1-1范围");
}
ImageIcon ii = new ImageIcon(originalFile.getCanonicalPath());
Image i = ii.getImage();
Image resizedImage = null;
int iWidth = i.getWidth(null);
int iHeight = i.getHeight(null);
// 图片不存在
if(iWidth == -1 || iHeight == -1){
return;
}
int newWidth = maxWidth;
if (iWidth < maxWidth) {
newWidth = iWidth;
}
if (iWidth >= iHeight) {
resizedImage = i.getScaledInstance(newWidth, (newWidth * iHeight)
/ iWidth, Image.SCALE_SMOOTH);
}
int newHeight = maxHeight;
if (iHeight < maxHeight) {
newHeight = iHeight;
}
if (resizedImage == null && iHeight >= iWidth) {
resizedImage = i.getScaledInstance((newHeight * iWidth) / iHeight,
newHeight, Image.SCALE_SMOOTH);
}
//此代码确保加载图像中的所有像素
Image temp = new ImageIcon(resizedImage).getImage();
if(temp != null){
try{
//创建缓冲图像
BufferedImage bufferedImage = new BufferedImage(temp.getWidth(null),
temp.getHeight(null), BufferedImage.TYPE_INT_RGB);
//将图像复制到缓冲图像
Graphics g = bufferedImage.createGraphics();
//清除背景并绘制图像。
g.setColor(Color.white);
g.fillRect(0, 0, temp.getWidth(null), temp.getHeight(null));
g.drawImage(temp, 0, 0, null);
g.dispose();
float softenFactor = 0.05f;
float[] softenArray = {0, softenFactor, 0, softenFactor,
1 - (softenFactor * 4), softenFactor, 0, softenFactor, 0};
Kernel kernel = new Kernel(3, 3, softenArray);
ConvolveOp cOp = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
bufferedImage = cOp.filter(bufferedImage, null);
// 一些老的Java代码在JDK1.7下编译会报错,比如这个:程序包com.sun.image.codec.jpeg不存在
// JPEGImageEncoder是sun公司的私有实现
// 使用统一的ImageIO进行图像格式文件的读写,没有必要使用过时的实现类JPEGImageEncoder类
/* //将jpeg写入文件
FileOutputStream out = new FileOutputStream(resizedFile);
//将图像编码为jpeg数据流
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bufferedImage);
param.setQuality(quality, true);
encoder.setJPEGEncodeParam(param);
encoder.encode(bufferedImage);
out.close();*/
// 获取文件格式(jpg、jpeg等)
// String formatName = fname.substring(fname.lastIndexOf(".") + 1);
// 以下formatName参数必须为jpg,其他格式时压缩图片可能比原图片大
// 生成压缩文件
ImageIO.write(bufferedImage, "jpg" , resizedFile);
System.out.println("图片压缩成功");
}catch (Exception ex){
System.out.println(ex.toString());
}
}
}