国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術文章
文章詳情頁

Java 實現圖片壓縮的兩種方法

瀏覽:52日期:2022-08-25 09:28:48

問題背景。

典型的情景:Nemo社區中,用戶上傳的圖片免不了要在某處給用戶做展示。

如用戶上傳的頭像,那么其他用戶在瀏覽該用戶信息的時候,就會需要回顯頭像信息了。

用戶上傳的原圖可能由于清晰度較高而體積也相對較大,考慮用戶流量帶寬,一般而言我們都不會直接體積巨大的原圖直接丟給用戶讓用戶慢慢下載。

這時候通常我們會在服務器對圖片進行壓縮,然后把壓縮后的圖片內容回顯給用戶。

壓縮方案:

這里主要找了兩個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 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('');}}

重點在于:

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 實現圖片壓縮的兩種方法的詳細內容,更多關于Java 圖片壓縮的資料請關注好吧啦網其它相關文章!

標簽: Java
相關文章:
主站蜘蛛池模板: 繁昌县| 嫩江县| 互助| 巴南区| 六枝特区| 甘德县| 秦安县| 固始县| 兰西县| 滦平县| 大方县| 华蓥市| 乳源| 平凉市| 萝北县| 馆陶县| 汶川县| 香河县| 中阳县| 嘉黎县| 鸡西市| 彰武县| 绵竹市| 海伦市| 全南县| 民丰县| 阿拉善右旗| 荔浦县| 武胜县| 黄龙县| 定日县| 霍城县| 丁青县| 南召县| 庆元县| 长垣县| 应城市| 永登县| 泰安市| 原平市| 桂东县|