對圖片進行等比例壓縮
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());
}