图片压缩代码操作:
需要压缩的原图片路径为 src;
压缩后存放的路径为 dist;
需要压缩的宽度为 width;
需要压缩的后的高度为 height;
File srcfile=new File(src);
//原图片是否存在
if(!srcfile.exists()){
return;
}
BufferedImage image=ImageIO.read(srcfile);
double ratio=1.0;
if(image.getHeight()>height){
ratio=height/image.getHeight();
}
//计算新生成图片的宽和高
int newWidth=(int)(image.getWidth()*ratio);
int newHeight=(int)(image.getHeight()*ratio);
BufferedImage bfImage=new BufferedImage(newWidth,newHeight,BufferedImage.TYPE_3BYTE_BGR);
//绘制缩小后的图
bfImage.getGraphics().drawImage(image.getScaledInstance(newWidth,newHeight,Image.SCALE_SMOOTH),0,0,null);
// 输出到文件流
FileOutputStream os=new FileOutputStream(dist);
JPEGImageEncoder encoder=JPEGCodec.createJPEGEncoder(os);
encoder.encoder(bfImage);
os.close();
代码中有两个常量第一个为:BufferedImage.TYPE_3BYTE_BGR
常量寓意和可替换的参数如下图:
第二个常量为: SCALE_SMOOTH 缩略算法 生成缩略图片的平滑度的 优先级比速度高 生成的图片质量比较好 但速度慢