可以将像素高的图片转成像素低的图片,同时图片清晰度会降低
jdk1.5之前的不支持
PNG格式的图片,之后支持,下面先来一个传进文件传出文件方式的:
class="java">
package com.oct.com;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageTypeSpecifier;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
/**
* 图片压缩
* @author hero
*
*/
public class ImgCompress {
public static void main(String[] args) {
ImgCompress.compressPic("C:\\img.jpg", "d:\\xxx.jpg");
}
/**
* 图片压缩
* @param srcFilePath
* @param descFilePath
* @return
*/
public static boolean compressPic(String srcFilePath,String descFilePath){
File file = null;
BufferedImage src = null;
FileOutputStream out = null;
ImageWriter imgWriter;
ImageWriteParam imgWriterParams;
//指定写图片的方式为jpg
imgWriter = ImageIO.getImageWritersByFormatName("jpg").next();
/**
* 写参数
*/
imgWriterParams = new JPEGImageWriteParam(null);
//要使用压缩,必须指定压缩方式为mode_ex...
imgWriterParams.setCompressionMode(imgWriterParams.MODE_EXPLICIT);
//这里指定压缩的程度,参数qulity是取值0~1范围内
imgWriterParams.setCompressionQuality((float)0.1);
imgWriterParams.setProgressiveMode(imgWriterParams.MODE_DISABLED);
ColorModel colorModel = ColorModel.getRGBdefault();
//指定压缩时使用的彩色模式
imgWriterParams.setDestinationType(new ImageTypeSpecifier(colorModel,
colorModel.createCompatibleSampleModel(16, 16)));
try {
if(!ImgCompress.isBlanck(srcFilePath)){
return false;
}else{
file = new File(srcFilePath);
src = ImageIO.read(file);//缓存图片
out = new FileOutputStream(descFilePath);//文件输出流
imgWriter.reset();
//必须先指定out值,才能调用write方法,ImageOutputStream可以通过任何
//OutputStream
imgWriter.setOutput(ImageIO.createImageOutputStream(out));
imgWriter.write(null,new IIOImage(src, null, null),imgWriterParams);
out.flush();
out.close();
}
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
private static boolean isBlanck(String imgPath){
File file = new File(imgPath);
return file.exists();
}
}