import java.awt.Dimension;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.IOException; import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import java.io.File;
import javax.imageio.ImageIO; /**
* JPG图片压缩工具
* @author clj
*
*/
public class ImageUtil {
/**
* 将原图src压缩后存入des中
* @param src 原图片文件
* @param des 压缩后的存储文件
* @param imgSize 图片缩放的最大尺寸
* @param quality 图片质量0~1
*/
public static void compress(File src,File des, int imgSize,float quality) {
FileOutputStream out = null;
try {
//读取源图片到内存中
Image image = ImageIO.read(src);
//获得压缩尺寸
Dimension dim = getRectangle(image.getWidth(null), image.getHeight(null),imgSize);
//在内存中创建压缩图片的缓冲区
BufferedImage tmpImg=new BufferedImage(dim.width,dim.height ,BufferedImage.TYPE_3BYTE_BGR);
//在缓冲区按缩放后的大小绘制压缩图片
tmpImg.getGraphics().drawImage(image.getScaledInstance(dim.width,dim.height,Image.SCALE_SMOOTH), 0, 0, null);
//设置图片质量,
JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(tmpImg);
jep.setQuality(quality, true);
//保存压缩图片
//输出图片存在则先删除
if(des.exists()){
des.delete();
}
//获得输出流
out = new FileOutputStream(des);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(tmpImg);
} catch (Exception ex) {
ex.printStackTrace();
}finally{
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} /**
* 获得压缩图片尺寸
* 最长边压缩为size px,短边按比例变化
* @param width
* @param height
* @return
*/
private static Dimension getRectangle( int width, int height, int size){
Dimension dim = new Dimension();
double w = width+0.0;
double h = height + 0.0;
double rate = w/h;
//宽或高大于size时,将较大者缩小为size,较小者则按比例变化
if(w > h && w > size){
w = size;
h = w / rate;
}else if(h > w && h > size){
h = size;
w = h*rate;
}
width = (int)w;
height = (int)h;
dim.width = width;
dim.height = height;
return dim;
} public static void main(String args[]){
ImageUtil.compress(new File("D:/test/img/src.jpg"), new File("D:/test/img/out.jpg"),600,1f);
}
}
05-11 13:55