importjava.io.*;importjava.awt.*;importjava.awt.image.*;importcom.sun.image.codec.jpeg.*;/***
Title:
*
Description:
*
Copyright: Copyright (c)2007-6-13
*
Company: fuen
*@author杨振朋
*@version1.0*/publicclassccc {privateString srcFile;privateString destFile;privateintwidth;privateintheight;privateImage img;/*** 构造函数
*@paramfileName String
*@throwsIOException*/publicccc(String fileName)throwsIOException {
File _file=newFile(fileName);//读入文件this.srcFile=_file.getName();this.destFile="c:/aa.jpg";//this.srcFile.substring(0, this.srcFile.lastIndexOf(".")) +"_s.jpg";img=javax.imageio.ImageIO.read(_file);//构造Image对象width=img.getWidth(null);//得到源图宽height=img.getHeight(null);//得到源图长}/*** 强制压缩/放大图片到固定的大小
*@paramw int 新宽度
*@paramh int 新高度
*@throwsIOException*/publicvoidresize(intw,inth)throwsIOException {
BufferedImage _image=newBufferedImage(w, h,BufferedImage.TYPE_INT_RGB);
_image.getGraphics().drawImage(img,0,0, w, h,null);//绘制缩小后的图FileOutputStream newimageout=newFileOutputStream(destFile);//输出到文件流/** JPEGImageEncoder 将图像缓冲数据编码为 JPEG 数据流。该接口的用户应在 Raster
* 或 BufferedImage 中提供图像数据,在 JPEGEncodeParams 对象中设置必要的参数,
* 并成功地打开 OutputStream(编码 JPEG 流的目的流)。JPEGImageEncoder 接口可
* 将图像数据编码为互换的缩略 JPEG 数据流,该数据流将写入提供给编码器的 OutputStream 中。
注意:com.sun.image.codec.jpeg 包中的类并不属于核心 Java API。它们属于 Sun 发布的
JDK 和 JRE 产品的组成部分。虽然其它获得许可方可能选择发布这些类,但开发人员不能寄
希望于从非 Sun 实现的软件中得到它们。我们期望相同的功能最终可以在核心 API 或标准扩
展中得到。*/JPEGImageEncoder encoder=JPEGCodec.createJPEGEncoder(newimageout);
encoder.encode(_image);//近JPEG编码newimageout.close();
}/*** 按照固定的比例缩放图片
*@paramt double 比例
*@throwsIOException*/publicvoidresize(doublet)throwsIOException {intw=(int) (width*t);inth=(int) (height*t);
resize(w, h);
}/*** 以宽度为基准,等比例放缩图片
*@paramw int 新宽度
*@throwsIOException*/publicvoidresizeByWidth(intw)throwsIOException {inth=(int) (height*w/width);
resize(w, h);
}/*** 以高度为基准,等比例缩放图片
*@paramh int 新高度
*@throwsIOException*/publicvoidresizeByHeight(inth)throwsIOException {intw=(int) (width*h/height);
resize(w, h);
}/*** 按照最大高度限制,生成最大的等比例缩略图
*@paramw int 最大宽度
*@paramh int 最大高度
*@throwsIOException*/publicvoidresizeFix(intw,inth)throwsIOException {if(width/height>w/h) {
resizeByWidth(w);
}else{
resizeByHeight(h);
}
}/*** 设置目标文件名
* setDestFile
*@paramfileName String 文件名字符串*/publicvoidsetDestFile(String fileName)throwsException {if(!fileName.endsWith(".jpg")) {thrownewException("Dest File Must end with \".jpg\".");
}
destFile=fileName;
}/*** 获取目标文件名
* getDestFile*/publicString getDestFile() {returndestFile;
}/*** 获取图片原始宽度
* getSrcWidth*/publicintgetSrcWidth() {returnwidth;
}/*** 获取图片原始高度
* getSrcHeight*/publicintgetSrcHeight() {returnheight;
}/** 调用测试*/publicstaticvoidmain(String[] args)throwsException {
ccc ccc=newccc("c:/image2.jpg");
ccc.resizeFix(500,300);
}
}