【www.bbyears.com--js教程】
直接上java图片压缩code:
代码如下
importjava.awt.Image;
importjava.awt.image.BufferedImage;
importjava.io.ByteArrayOutputStream;
importjava.io.IOException;
importjava.io.InputStream;
importjavax.imageio.ImageIO;
publicclassImageProcess {
/**
* 图片
*/
privateImage img;
/**
* 宽度
*/
privateintwidth;
/**
* 高度
*/
privateintheight;
/**
* 文件格式
*/
privateString imageFormat;
/**
* 构造函数
* @throws Exception
*/
publicImageProcess(InputStream in,String fileName)throwsException{
//构造Image对象
img = ImageIO.read(in);
//得到源图宽
width = img.getWidth(null);
//得到源图长
height = img.getHeight(null);
//文件格式
imageFormat = fileName.substring(fileName.lastIndexOf(".")+1);
}
/**
* 按照宽度还是高度进行压缩
* @param w int 最大宽度
* @param h int 最大高度
*/
publicbyte[] resizeFix(intw,inth)throwsIOException {
if(width / height > w / h) {
returnresizeByWidth(w);
}else{
returnresizeByHeight(h);
}
}
/**
* 以宽度为基准,等比例放缩图片
* @param w int 新宽度
*/
publicbyte[] resizeByWidth(intw)throwsIOException {
inth = (int) (height * w / width);
returnresize(w, h);
}
/**
* 以高度为基准,等比例缩放图片
* @param h int 新高度
*/
publicbyte[] resizeByHeight(inth)throwsIOException {
intw = (int) (width * h / height);
returnresize(w, h);
}
/**
* 强制压缩/放大图片到固定的大小
* @param w int 新宽度
* @param h int 新高度
*/
publicbyte[] resize(intw,inth)throwsIOException {
// SCALE_SMOOTH 的缩略算法 生成缩略图片的平滑度的 优先级比速度高 生成的图片质量比较好 但速度慢
BufferedImage image =newBufferedImage(w, h,BufferedImage.TYPE_INT_RGB );
image.getGraphics().drawImage(img,0,0, w, h,null);// 绘制缩小后的图
ByteArrayOutputStream baos =newByteArrayOutputStream();
ImageIO.write(image, imageFormat, baos);
returnbaos.toByteArray();
}
}