無需 Servlet、無需 Web 容器,純 Java SE 即可生成圖片文件:
BufferedImage 作為畫布Graphics 繪製圖形/文字JPEGImageEncoder 將圖像編碼寫入文件流import java.io.*;
import java.util.*;
import com.sun.image.codec.jpeg.*;
import java.awt.image.*;
import java.awt.*;
public class JeruGraphics {
BufferedImage image;
// 創建 jpg 文件到指定路徑
public void createJpg(String path) {
try {
FileOutputStream fos = new FileOutputStream(path);
BufferedOutputStream bos = new BufferedOutputStream(fos);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(bos);
encoder.encode(image);
bos.close();
} catch (FileNotFoundException fnfe) {
System.out.println(fnfe);
} catch (IOException ioe) {
System.out.println(ioe);
}
}
public static void main(String[] args) {
int width = 400, height = 200;
int xLength = 300, yLength = 150;
int count = 5;
Vector data = new Vector();
data.addElement(new Integer(100));
data.addElement(new Integer(120));
data.addElement(new Integer(150));
data.addElement(new Integer(40));
data.addElement(new Integer(5));
JeruGraphics jg = new JeruGraphics();
jg.image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = jg.image.getGraphics();
// 畫坐標系
g.setColor(Color.white);
g.fillRect(0, 0, width, height);
g.setColor(Color.blue);
g.drawLine(10, height - 10, 10, height - 10 - yLength); // Y 軸
g.drawLine(10, height - 10, 10 + xLength, height - 10); // X 軸
// 畫折線圖
int yTo;
int yFrom = ((Integer) data.elementAt(0)).intValue();
for (int i = 1; i < count; i++) {
yTo = ((Integer) data.elementAt(i)).intValue();
g.drawLine(10 + i * xLength / count, height - 10,
10 + i * xLength / count, height - 15); // X 軸刻度
g.drawLine(10 + (i - 1) * xLength / count, yFrom,
10 + i * xLength / count, yTo); // 數據連線
yFrom = yTo;
}
jg.createJpg("d:\\aaa.jpg");
System.out.println("圖片生成完成:d:\\aaa.jpg");
}
}
BufferedImage.TYPE_INT_RGB:8 位 RGB 色彩模型,適合 JPGcom.sun.image.codec.jpeg.JPEGCodec:Sun 私有 API,JDK 內置,無需額外依賴(JDK 9+ 建議改用 ImageIO.write())Vector 存 Integer,現代代碼建議用 List<Integer>g.drawString())ImageIO.write(image, "png", file))幾十行代碼即可實現「命令行生成圖片」,適合輕量級報表、驗證碼生成、自動化測試截圖對比等場景。簡單、實用、極具參考價值。