使用 java.awt.Image、BufferedImage 與 JPEGImageEncoder 可實作影像縮放並儲存為 JPEG。本文提供一個可直接呼叫的工具類別。
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import com.sun.image.codec.jpeg.*;
public class ImageResizer {
/**
* 縮放影像並儲存為 JPEG
* @param path 目錄路徑
* @param srcFile 來源檔名
* @param destFile 目標檔名
* @param scale 倍數(大於 1 放大,小於 1 縮小)
*/
public void resize(String path, String srcFile, String destFile, double scale) {
try {
File src = new File(path, srcFile);
Image img = ImageIO.read(src);
int w = (int) (img.getWidth(null) * scale);
int h = (int) (img.getHeight(null) * scale);
BufferedImage tag = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(img, 0, 0, w, h, null);
FileOutputStream out = new FileOutputStream(new File(path, destFile));
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(tag);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new ImageResizer().resize("E:\\", "1.bmp", "2.jpg", 0.5);
}
}
com.sun.image.codec.jpeg 為 Sun 專有 API,Java 9+ 已移除,建議改用 ImageIO.write(bufferedImage, "jpg", outputStream) 搭配 ImageWriteParam 設定品質。RenderingHints 設定雙三次插值:g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC)。