標籤:param img puts 縮放 resize 縮圖 exception phi 縮放圖片
package com.test;import com.sun.image.codec.jpeg.JPEGCodec;import com.sun.image.codec.jpeg.JPEGImageEncoder;import org.junit.Test;import javax.imageio.ImageIO;import java.awt.*;import java.awt.image.BufferedImage;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;/** *圖片壓縮 */public class ImageTest { private Image img; private int width; private int height; @Test public void test(){ try{ //壓縮開始 ImageTest imgCom = new ImageTest("D://1.png"); imgCom.resizeFix(400, 400,"D://2.png"); //壓縮結束 }catch (Exception e){ e.printStackTrace(); } } /** * 建構函式 * @param fileName 圖片路徑 * @throws IOException */ public ImageTest(String fileName) throws IOException { // 讀入檔案 File file = new File(fileName); // 構造Image對象 img = ImageIO.read(file); // 得到源圖寬 width = img.getWidth(null); // 得到源圖長 height = img.getHeight(null); } /** * 按照寬度還是高度進行壓縮 * @param w int 最大寬度 * @param h int 最大高度 * @param filePath 圖片路徑 * @throws IOException */ public void resizeFix(int w, int h,String filePath) throws IOException { if (width / height > w / h) { resizeByWidth(w,filePath); } else { resizeByHeight(h,filePath); } } /** * 以寬度為基準,等比例放縮圖片 * @param w int 新寬度 * @param filePath 圖片路徑 * @throws IOException */ public void resizeByWidth(int w,String filePath) throws IOException { int h = (int) (height * w / width); resize(w, h,filePath); } /** * 以高度為基準,等比例縮放圖片 * @param h int 新高度 * @param filePath 圖片路徑 * @throws IOException */ public void resizeByHeight(int h,String filePath) throws IOException { int w = (int) (width * h / height); resize(w, h,filePath); } /** * 強制壓縮/放大圖片到固定的大小 * @param w int 新寬度 * @param h int 新高度 * @param filePath * @throws IOException */ public void resize(int w, int h,String filePath) throws IOException { // SCALE_SMOOTH 的縮減演算法 產生縮圖片的平滑度的 優先順序比速度高 產生的圖片品質比較好 但速度慢 BufferedImage image = new BufferedImage(w, h,BufferedImage.TYPE_INT_RGB ); // 繪製縮小後的圖 image.getGraphics().drawImage(img, 0, 0, w, h, null); File destFile = new File(filePath); // 輸出到檔案流 FileOutputStream out = new FileOutputStream(destFile); // 可以正常實現bmp、png、gif轉jpg JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); // JPEG編碼 encoder.encode(image); out.close(); }}
Java圖片壓縮