1.需要导入的jar包
2.定义类的私有字段
3.有参和无参构造
/**
* 无参构造(一般在存在有参构造的情况的需要另写一个无参构造,防止系统将有参构造默认为需要自动执行的方法,防止报错)
*/
public ImgCompress() {
super();
}
/**
* 有参构造(调用的时候直接 new ImgCompress(params)就可以了,不需要写 .setParams() 了 )
*
* @param fileName
* 文件名
* @throws IOException
*/
public ImgCompress(String fileName) throws IOException {
File file = new File(fileName);// 读入文件
img = ImageIO.read(file); // 构造Image对象
width = img.getWidth(null); // 得到源图宽
height = img.getHeight(null); // 得到源图长
}
3.以何种压缩方法
/**
* 判断按照宽度还是高度进行压缩
*
* @param w
* 最大宽度
* @param h
* 最大高度
* @throws IOException
*/
public void resizeFix(int w, int h) throws IOException {
if (width / height > w / h) {
resizeByWidth(w);
} else {
resizeByHeight(h);
}
}
/**
* 以宽度为准,等比例缩放图片
*
* @param w
* 新宽度
* @throws IOException
*/
public void resizeByWidth(int w) throws IOException {
int h = (int) (height * w / width);
resize(w, h);
}
/**
* 以高度为准,等比例缩放图片
*
* @param h
* 新高度
* @throws IOException
*/
public void resizeByHeight(int h) throws IOException {
int w = (int) (width * h / height);
resize(w, h);
}
4.强制压缩/方法图片
/**
* 强制压缩/放大图片到固定的大小
*
* @param w
* int 新宽度
* @param h
* int 新高度
*/
public void resize(int w, int h) throws IOException {
// SCALE_SMOOTH 的缩略算法 生成缩略图片的平滑度的 优先级比速度高 生成的图片质量比较好 但速度慢
BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
image.getGraphics().drawImage(img, 0, 0, w, h, null); // 绘制缩小后的图
File destFile = new File("E:\\处理后文件\\456.jpg");
FileOutputStream out = new FileOutputStream(destFile); // 输出到文件流
// 可以正常实现bmp、png、gif转jpg
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(image); // JPEG编码
out.close();
}
5.测试方法
/**
* main函数 测试
*
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
System.out.println("开始:" + new Date().toString());
ImgCompress imgCom = new ImgCompress("E:\\源文件\\1111.png");
imgCom.resizeFix(400, 400);
System.out.println("结束:" + new Date().toString());
}