1.情景展示
在實際生活中,隨着圖片的質量和尺寸越來越大,我們在用圖片進行網絡傳輸的時候,往往受制於網速或者網站的影響,導致圖片加載不出來;
沒有辦法的辦法,就是:通過壓縮圖片的質量(清晰度)或者圖片的尺寸(大小、像素),在java中,如何實現?
2.准備工作
我參考了網上通過java來實現的縮小圖片尺寸的方法,不好使;
最終選擇了Thumbnailator已經封裝好的方法來調用,雖然已經是5前的代碼了,但是,相較於java自身硬編碼實現而言,依舊有很大優勢。
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.8</version>
</dependency>
3.解決方案
代碼實現:
/*
* 對圖片進行等比縮小或放大
* @attention:
* Thumbnails可以將修改后的圖片轉換成OutputStream、BufferedImage或者File
* @date: 2022/2/16 18:37
* @param: imgInputPath 原圖片路徑
* @param: imgOutputPath 圖片輸出路徑
* 可以更改原圖片的格式(比如:原圖片是png格式,我們可以在讓其生成的時候變成非png格式)
* @param: scale 圖片比例
* @return: boolean 成功、失敗
*/
public static boolean compressPicBySize(String imgInputPath, String imgOutputPath, float scale) {
boolean flag = false;
String imgStatus = (scale > 1) ? "放大" : "縮小";
try {
Thumbnails.of(imgInputPath).scale(scale).toFile(imgOutputPath);
// 成功
flag = true;
log.info("圖片{}成功", imgStatus);
} catch (IOException e) {
e.printStackTrace();
log.error("圖片{}失敗:{}", imgStatus, e.getMessage());
}
return flag;
}
測試:
public static void main(String[] args) {
compressPicBySize("C:\\Users\\Marydon\\Desktop\\wxd.png", "C:\\Users\\Marydon\\Desktop\\wxd.bmp", 0.1F);// 縮小到原來的10%
}
我們可以看到:圖片的尺寸相較於之前減少了90%。
如果想要,指定修改后的圖片大小,可以使用下面這種方式:
查看代碼
/*
* 改變原圖片尺寸
* @attention:
* @date: 2022/2/16 18:17
* @param: imgPath 原圖片路徑
* @param: width 改變后的圖片寬度
* @param: height 改變后的圖片高度
* @param: format 輸出圖片格式
* @return: byte[] 改變后的圖片流
*/
public static byte[] changeImgSize(String imgPath, int width, int height, String format) {
byte[] changedImage = null;
ByteArrayOutputStream out = null;
format = StringUtils.isNotEmpty(format) ? format : "png";
try {
out = new ByteArrayOutputStream();
Thumbnails.of(imgPath).size(width, height).outputFormat(format).toOutputStream(out);
changedImage = out.toByteArray();
} catch (IOException e) {
log.error(e.getMessage());
} finally {
// 關閉流
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return changedImage;
}
最后,如果想要壓縮圖片體積,不想更改原圖片尺寸的話,見文末推薦。
