Java 實現(xiàn)圖片壓縮的兩種方法
問題背景。
典型的情景:Nemo社區(qū)中,用戶上傳的圖片免不了要在某處給用戶做展示。
如用戶上傳的頭像,那么其他用戶在瀏覽該用戶信息的時候,就會需要回顯頭像信息了。
用戶上傳的原圖可能由于清晰度較高而體積也相對較大,考慮用戶流量帶寬,一般而言我們都不會直接體積巨大的原圖直接丟給用戶讓用戶慢慢下載。
這時候通常我們會在服務(wù)器對圖片進行壓縮,然后把壓縮后的圖片內(nèi)容回顯給用戶。
壓縮方案:
這里主要找了兩個java中常用的圖片壓縮工具庫:Graphics和Thumbnailator。
1、Graphics:
/**
* compressImage
*
* @param imageByte
* Image source array
* @param ppi
* @return
*/
public static byte[] compressImage(byte[] imageByte, int ppi) {
byte[] smallImage = null;
int width = 0, height = 0;
if (imageByte == null)
return null;
ByteArrayInputStream byteInput = new ByteArrayInputStream(imageByte);
try {
Image image = ImageIO.read(byteInput);
int w = image.getWidth(null);
int h = image.getHeight(null);
// adjust weight and height to avoid image distortion
double scale = 0;
scale = Math.min((float) ppi / w, (float) ppi / h);
width = (int) (w * scale);
width -= width % 4;
height = (int) (h * scale);
if (scale >= (double) 1)
return imageByte;
BufferedImage buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
buffImg.getGraphics().drawImage(image.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
ByteArrayOutputStream out = new ByteArrayOutputStream();
ImageIO.write(buffImg, "png", out);
smallImage = out.toByteArray();
return smallImage;
} catch (IOException e) {
log.error(e.getMessage());
throw new RSServerInternalException("");
}
}
重點在于:
BufferedImage buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); buffImg.getGraphics().drawImage(image.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
2、Thumbnailator:
/**
* compressImage
*
* @param path
* @param ppi
* @return
*/
public static byte[] compressImage(String path, int ppi) {
byte[] smallImage = null;
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
Thumbnails.of(path).size(ppi, ppi).outputFormat("png").toOutputStream(out);
smallImage = out.toByteArray();
return smallImage;
} catch (IOException e) {
log.error(e.getMessage());
throw new RSServerInternalException("");
}
}
實際測試中,批量的情境下,后者較前者更快一些。
以上就是Java 實現(xiàn)圖片壓縮的兩種方法的詳細內(nèi)容,更多關(guān)于Java 圖片壓縮的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Java中static修飾的靜態(tài)變量、方法及代碼塊的特性與使用
這篇文章主要介紹了Java中static修飾的靜態(tài)變量、方法及代碼塊的特性與使用,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-04-04
java實現(xiàn)操作系統(tǒng)中的最佳置換Optimal算法
這篇文章主要介紹了java實現(xiàn)操作系統(tǒng)中的最佳置換Optimal算法 ,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-02-02
Mybatis-plus操作json字段實戰(zhàn)教程
這篇文章主要介紹了Mybatis-plus操作json字段實戰(zhàn)教程,本文結(jié)合實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-02-02
Springmvc請求參數(shù)類型轉(zhuǎn)換器及原生api代碼實例
這篇文章主要介紹了Springmvc請求參數(shù)類型轉(zhuǎn)換器及原生api代碼實例,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-10-10
Spring?AOP實現(xiàn)聲明式事務(wù)機制源碼解析
這篇文章主要為大家介紹了Spring?AOP實現(xiàn)聲明式事務(wù)機制源碼解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-12-12

