Java 實(shí)現(xiàn)圖片壓縮的兩種方法
問(wèn)題背景。
典型的情景:Nemo社區(qū)中,用戶上傳的圖片免不了要在某處給用戶做展示。
如用戶上傳的頭像,那么其他用戶在瀏覽該用戶信息的時(shí)候,就會(huì)需要回顯頭像信息了。
用戶上傳的原圖可能由于清晰度較高而體積也相對(duì)較大,考慮用戶流量帶寬,一般而言我們都不會(huì)直接體積巨大的原圖直接丟給用戶讓用戶慢慢下載。
這時(shí)候通常我們會(huì)在服務(wù)器對(duì)圖片進(jìn)行壓縮,然后把壓縮后的圖片內(nèi)容回顯給用戶。
壓縮方案:
這里主要找了兩個(gè)java中常用的圖片壓縮工具庫(kù):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 distortiondouble 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('');}}
重點(diǎn)在于:
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(''); }}
實(shí)際測(cè)試中,批量的情境下,后者較前者更快一些。
以上就是Java 實(shí)現(xiàn)圖片壓縮的兩種方法的詳細(xì)內(nèi)容,更多關(guān)于Java 圖片壓縮的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. 存儲(chǔ)于xml中需要的HTML轉(zhuǎn)義代碼2. python 浮點(diǎn)數(shù)四舍五入需要注意的地方3. Java GZip 基于內(nèi)存實(shí)現(xiàn)壓縮和解壓的方法4. python開發(fā)一款翻譯工具5. 利用CSS制作3D動(dòng)畫6. jsp+servlet簡(jiǎn)單實(shí)現(xiàn)上傳文件功能(保存目錄改進(jìn))7. Springboot 全局日期格式化處理的實(shí)現(xiàn)8. 完美解決vue 中多個(gè)echarts圖表自適應(yīng)的問(wèn)題9. SpringBoot+TestNG單元測(cè)試的實(shí)現(xiàn)10. PHP實(shí)現(xiàn)簡(jiǎn)單線性回歸之?dāng)?shù)學(xué)庫(kù)的重要性
