import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
public class ImageCompress {
private Image img;
private int width;
private int height;
/**
* 構造函數
* 沒有蠟筆的小新
* @throws IOException
*/
public ImageCompress(String fileName) throws IOException {
File file = new File(fileName);// 讀入文件
img = ImageIO.read(file); // 構造Image對象
width = img.getWidth(null); // 得到源圖寬
height = img.getHeight(null); // 得到源圖長
}
/**
* 按照寬度還是高度進行壓縮
*
* @param w
* int 最大寬度
* @param h
* int 最大高度
*/
public void resizeFix(int w, int h) throws IOException {
if (width / height > w / h) {
resizeByWidth(w);
} else {
resizeByHeight(h);
}
}
/**
* 以寬度爲基準,等比例放縮圖片
*
* @param w int 新寬度
*/
public void resizeByWidth(int w) throws IOException {
int h = (int) (height * w / width);
resize(w, h);
}
/**
* 以高度爲基準,等比例縮放圖片
*
* @param h
* int 新高度
*/
public void resizeByHeight(int h) throws IOException {
int w = (int) (width * h / height);
resize(w, h);
}
/**
* 強制壓縮/放大圖片到固定的大小
*
* @param w int 新寬度
* @param h int 新高度
*/
public void resize(int w, int h) 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("C:\\Users\\Administrator\\Desktop\\1.jpg");
FileOutputStream out = new FileOutputStream(destFile); // 輸出到文件流
// 可以正常實現bmp、png、gif轉jpg
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(image); // JPEG編碼
out.close();
}
}
個人說明:由於這是在網上找的方法,經過測試之後感覺還不錯,留作自己的方法積累。