1. 程式人生 > 其它 >工具類|Java實現圖片等比例壓縮,支援png&jpg格式

工具類|Java實現圖片等比例壓縮,支援png&jpg格式

技術標籤:工具類java

做圖片上傳專案,特別是基於網際網路專案的,往往要考慮到圖片到圖片不能太大,太大可能影響載入速度和使用者體驗,如果在前端做大小限制,讓使用者去處理圖片大小,有點太不人性化了。程式能解決的事情,就不讓發生在使用者端。

程式碼比較簡單,直接上程式碼:

package com.fengchen.image;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;

import javax.imageio.
ImageIO; import com.sun.image.codec.jpeg.JPEGCodec; import com.sun.image.codec.jpeg.JPEGImageEncoder; public class ImageHelper { /** * 建立圖片縮圖,進行等比例壓縮 * * @param src 源圖片檔案完整路徑 * @param dist 目標圖片檔案完整路徑 * @param width 縮放的寬度 * @param height 縮放的高度 */ public static void compress(String src,
String dist, float width, float height) { try { File srcfile = new File(src); if (!srcfile.exists()) { System.out.println("檔案不存在"); return; } BufferedImage image = ImageIO.read(srcfile); // 獲得縮放的比例 double ratio = 1.0; // 判斷如果高、寬都不大於設定值,則不處理 if (image.getHeight
() > height || image.getWidth() > width) { if (image.getHeight() > image.getWidth()) { ratio = height / image.getHeight(); } else { ratio = width / image.getWidth(); } } // 計算新的圖面寬度和高度 int newWidth = (int) (image.getWidth() * ratio); int newHeight = (int) (image.getHeight() * ratio); BufferedImage bfImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB); bfImage.getGraphics().drawImage(image.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH), 0, 0, null); FileOutputStream os = new FileOutputStream(dist); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os); encoder.encode(bfImage); os.close(); System.out.println("建立縮圖成功"); } catch (Exception e) { System.out.println("建立縮圖發生異常" + e.getMessage()); } } }

推薦下大飛做的一個Java技術類公眾號“Java實戰寶典”,主要是收集一些日常工作中常用的工具類,一些實戰專案的教學及一些疑難問題整理。
在這裡插入圖片描述