Skip to content

Instantly share code, notes, and snippets.

@bombless
Created October 12, 2022 08:19
Show Gist options
  • Save bombless/68896a8ca8cdfb9c8bd9878bd0a49f12 to your computer and use it in GitHub Desktop.
Save bombless/68896a8ca8cdfb9c8bd9878bd0a49f12 to your computer and use it in GitHub Desktop.
Java Image processing
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
class Factory {
public static void main(String[] args) throws IOException {
String path = args[0];
String[] readFormats = ImageIO.getReaderFormatNames(); // 可讀入的格式
String[] writerFormatNames = ImageIO.getWriterFormatNames(); // 可輸出的格式
System.out.println("可讀入的圖片格式:" + Arrays.asList(readFormats));
System.out.println("可輸出的圖片格式:" + Arrays.asList(writerFormatNames));
File imgFile = new File(path);
BufferedImage bufferedImage = ImageIO.read(imgFile); // 讀入檔案轉為 BufferedImage 物件
int exportWidth = bufferedImage.getWidth() / 2; // 要輸出的寬度
int exportHeight = bufferedImage.getHeight() / 2; // 要輸出的高度
// 讀入一個空白的 BufferedImage 物件,只定義 寬度、高度、輸出類型
BufferedImage emptyImage = new BufferedImage(exportWidth, exportHeight, bufferedImage.getType());
// 用剛才建立的空白 BufferedImage 物件來建立畫布
Graphics2D g2d = emptyImage.createGraphics();
g2d.drawImage(
bufferedImage, // 把我們讀入的圖片畫上去
0, // x軸起始點
0, // y軸起始點
exportWidth, // 要畫上去的寬度
exportHeight, // 要畫上去的長度
null
);
g2d.dispose(); // 其實不用一定要用到 dispose() 方法,用了 dispose() 這個 g2d 就不能再被寫入內容了
// 建立一個 FileOutputStream 並且告訴他我們的目標輸出的位置
FileOutputStream os = new FileOutputStream(imgFile);
ImageIO.write(emptyImage, "png", os);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment