import java.awt.image.BufferedImage;
import java.io.File;import java.io.FileOutputStream;
import com.sun.image.codec.jpeg.*;
public class ImgCompresser {
public static void main(String[] args) throws Exception {File _file = new File("z://0-0.jpg");//读入文件
Image src = javax.imageio.ImageIO.read(_file);//构造Image对象
int width=src.getWidth(null);//得到源图宽
int height=src.getHeight(null);//得到源图长
//System.out.print(width+"*"+height);BufferedImage tag = new BufferedImage(width/3,height/3,BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(src,0,0,width/3,height/3,0,0,width,height,null); //绘制缩小后的图,八个数值前四个是绘制到新图片的区域后四个是读取原图片的区域,可实现裁剪缩放
FileOutputStream out=new FileOutputStream("z://0-0.min.jpg"); //输出到文件流JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(tag); //近JPEG编码
out.close();
} }
在Eclipse中处理图片,需要引入两个包:
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
报错:
Access restriction: The type JPEGImageEncoder is not accessible due to restriction on required library C:\Java\jre1.6.0_07\lib\rt.jar
此时解决办法:
Eclipse默认把这些受访问限制的API设成了ERROR。只要把Windows-Preferences-Java-Complicer-Errors/Warnings里面的Deprecated and restricted API中的Forbidden references(access rules)选为Warning就可以编译通过并正常运行。
参考:
http://www.pconline.com.cn/pcedu/empolder/gj/java/0405/369776.html
http://hi.baidu.com/qiaosongshan/blog/item/5635950ec3ef910295ca6ba0.html