import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
/**
* 作成日期: 2009-11-13 下午02:12:53<br/>
* 修改者: <br/>
* 修改日期:<br/>
* 功能描述:压缩图片<br/>
*/
public class ImageCompresser {
public static void main(String args[]){
String srcUrl = "D:/My Documents/temp/p1.jpg";
String tarUrl = "D:/My Documents/temp/p2.jpg";
compressImage(srcUrl,tarUrl);
}
/**
* @function 压缩图片
* @param srcUrl 源图片路径
* @param tarUrl 目标图片路径
*/
public static void compressImage(String srcUrl,String tarUrl){
try {
File srcFile = new File(srcUrl);
//构造Image对象
Image srcImage = ImageIO.read(srcFile);
//获取图片的宽度和高度
int width = srcImage.getWidth(null);
int height = srcImage.getHeight(null);
//生成指定大小的画布
BufferedImage bi = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
//将源图片按指定的大小画在画布上
bi.getGraphics().drawImage(srcImage, 0, 0, width/2,height/2,null);
//输出流
FileOutputStream fos = new FileOutputStream(tarUrl);
//将图片以jpg的形式编码
JPEGImageEncoder imageEncoder = JPEGCodec.createJPEGEncoder(fos);
imageEncoder.encode(bi);
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}