package web.images;
import java.io.*;
import java.util.*;
import com.sun.image.codec.jpeg.*;
import java.awt.image.*;
import java.awt.*;
public class ChartGraphics {
BufferedImage image;
public void createImage(String fileLocation) {
try {
FileOutputStream fos = new FileOutputStream(fileLocation);
BufferedOutputStream bos = new BufferedOutputStream(fos);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(bos);
encoder.encode(image);
bos.close();
} catch (Exception e) {
System.out.println(e);
}
}
public void graphicsGeneration(int h1, int h2, int h3, int h4, int h5) {
final int X = 10;
int imageWidth = 800;
int imageHeight = 900;
int columnWidth = 70;
int columnHeight = 800;
ChartGraphics chartGraphics = new ChartGraphics();
chartGraphics.image = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB);
Graphics g = chartGraphics.image.getGraphics();
// 背景
g.setColor(Color.white);
g.fillRect(0, 0, imageWidth, imageHeight);
// 座標軸
g.setColor(Color.black);
g.drawLine(columnWidth + X, columnHeight - h5 - 50, columnWidth + X, columnHeight); // Y軸
g.drawLine(columnWidth + X, columnHeight - h5 - 50, columnWidth + X - 10, columnHeight - h5 - 40); // Y箭頭左
g.drawLine(columnWidth + X, columnHeight - h5 - 50, columnWidth + X + 10, columnHeight - h5 - 40); // Y箭頭右
g.drawLine(750, columnHeight, columnWidth + X, columnHeight); // X軸
g.drawLine(750, columnHeight, 740, columnHeight - 10); // X箭頭左
g.drawLine(750, columnHeight, 740, columnHeight + 10); // X箭頭右
// 柱狀條
g.setColor(Color.yellow);
g.fillRect(X + 1 * columnWidth + 10, columnHeight - h1, columnWidth, h1);
g.fillRect(X + 2 * columnWidth + 20, columnHeight - h2, columnWidth, h2);
g.fillRect(X + 3 * columnWidth + 30, columnHeight - h3, columnWidth, h3);
g.fillRect(X + 4 * columnWidth + 40, columnHeight - h4, columnWidth, h4);
g.fillRect(X + 5 * columnWidth + 50, columnHeight - h5, columnWidth, h5);
// 輸出
chartGraphics.createImage("D:\\leaderquery\\leaderqueryWeb\\web800\\images\\chart.jpg");
}
}
BufferedImage.TYPE_INT_RGB 創建內存圖像,避免閃爍JPEGCodec.createJPEGEncoder() 將內存圖像編碼為 JPEG 流g.drawString() 繪製刻度標籤與標題ImageIO.write(image, "jpg", file) (JDK 1.4+) 替代已過時的 com.sun.image.codec.jpeg 包response.getOutputStream() 實現動態圖片服務此示例展示了 Java 在服務端生成統計圖表的經典模式,代碼結構清晰,易於擴展為通用圖表組件。