直接貼出工具類源碼
package com.snow.web.util.publics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.imageio.ImageIO;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
/**
* 圖檔壓縮并儲存
* @author jingxue.chen
*
*/
public class ImgCompressUtil {
public static void main(String[] args) {
try {
ImgCompressUtil.compressFileName("D:\\logs\\0003.jpg", 100, 100, "D:\\logs", "0003-6.jpg");
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 根據圖檔的本地路徑壓縮圖檔并儲存
* @param fileUrl 圖檔存放全路徑【D:\\logs\\0003.jpg】
* @param width 儲存寬度
* @param height 儲存高度
* @param saveAddress 儲存路徑【D:\\logs】
* @param fileName 儲存檔案名【0003.jpg】
* @throws IOException
*/
public static void compressFileName(String fileUrl,int width,int height,String saveAddress,String fileName) throws IOException{
File file = new File(fileUrl);// 讀入檔案
Image img = ImageIO.read(file); // 構造Image對象
int imgWidth = img.getWidth(null); // 得到源圖寬
int imgHeight = img.getHeight(null); // 得到源圖長
if (imgWidth / imgHeight > width / height) {
int h = (int) (imgHeight * width / imgWidth);
resize(img,width, h,saveAddress,fileName);
} else {
int w = (int) (imgWidth * height / imgHeight);
resize(img,w, height,saveAddress,fileName);
}
}
/**
* 根據圖檔的本地路徑壓縮圖檔并儲存
* @param inputStream 圖檔檔案的檔案流
* @param width 儲存寬度
* @param height 儲存高度
* @param saveAddress 儲存路徑【D:\\logs】
* @param fileName 儲存檔案名【0003.jpg】
* @throws IOException
*/
public static void compressFileName(InputStream inputStream,int width,int height,String saveAddress,String fileName) throws IOException{
Image img = ImageIO.read(inputStream); // 構造Image對象
int imgWidth = img.getWidth(null); // 得到源圖寬
int imgHeight = img.getHeight(null); // 得到源圖長
if (imgWidth / imgHeight > width / height) {
int h = (int) (imgHeight * width / imgWidth);
resize(img,width, h,saveAddress,fileName);
} else {
int w = (int) (imgWidth * height / imgHeight);
resize(img,w, height,saveAddress,fileName);
}
}
/**
* 強制壓縮/放大圖檔到固定的大小
* @param img
* @param w int 新寬度
* @param h int 新高度
* @param saveAddress 檔案儲存位址
* @param fileName 檔案儲存名稱
*/
private static void resize(Image img, int newWidth, int newHeight, String saveAddress, String fileName) throws IOException {
BufferedImage newBufImg = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
newBufImg.getGraphics().drawImage(img.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH), 0, 0, null);
FileOutputStream output = new FileOutputStream(saveAddress+File.separator+fileName);
// JPEGImageEncoder可适用于其他圖檔類型的轉換
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(output);
encoder.encode(newBufImg);
output.close();
}
}
本地測試可用~~~