では、前回の「CSVを読み込んでGUIで棒グラフ表示」をさらに発展させて、そのグラフを画像ファイル(PNGなど)として保存するサンプルを紹介します。
サンプルコード:Swingの描画をPNGに保存
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import java.util.*;
public class FrequencyGraphToImage extends JPanel {
private Map<Integer, Integer> countMap;
public FrequencyGraphToImage(Map<Integer, Integer> countMap) {
this.countMap = countMap;
setPreferredSize(new Dimension(600, 400));
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (countMap == null || countMap.isEmpty()) return;
int maxCount = Collections.max(countMap.values());
int width = getWidth();
int height = getHeight();
int barWidth = width / countMap.size();
int i = 0;
for (Map.Entry<Integer, Integer> entry : countMap.entrySet()) {
int value = entry.getKey();
int count = entry.getValue();
int barHeight = (int) ((double) count / maxCount * (height - 50));
g.setColor(Color.BLUE);
g.fillRect(i * barWidth + 10, height - barHeight - 30, barWidth - 20, barHeight);
g.setColor(Color.BLACK);
g.drawString(String.valueOf(value), i * barWidth + (barWidth / 2) - 10, height - 10);
g.drawString(String.valueOf(count), i * barWidth + (barWidth / 2) - 10, height - barHeight - 35);
i++;
}
}
public static void main(String[] args) {
// ダミーデータ(本来はCSVから読み込む)
Map<Integer, Integer> countMap = new LinkedHashMap<>();
countMap.put(10, 3);
countMap.put(20, 2);
countMap.put(30, 5);
countMap.put(40, 1);
FrequencyGraphToImage panel = new FrequencyGraphToImage(countMap);
// --- 画像として保存 ---
BufferedImage image = new BufferedImage(600, 400, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = image.createGraphics();
panel.paint(g2);
g2.dispose();
try {
ImageIO.write(image, "png", new File("graph.png"));
System.out.println("グラフを graph.png として保存しました。");
} catch (IOException e) {
System.out.println("画像保存中にエラー: " + e.getMessage());
}
// --- GUI表示(確認用) ---
JFrame frame = new JFrame("出現回数グラフ");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
}
Java✅ 実行結果
- プログラムを実行するとウィンドウに棒グラフが表示されます
- 同時に、カレントディレクトリに graph.png が保存されます
- 保存された画像はExcelやWordに貼り付けたり、Webにアップロードしたりできます
ポイント
BufferedImageを作成し、panel.paint(g2)で描画内容を画像に転写ImageIO.write(image, "png", new File("graph.png"))でPNGファイルとして保存- GUI表示と画像保存を同時に行える
発展アイデア
- CSVから読み込んだデータをそのままグラフ化して保存
- 出力形式を
"jpg"や"gif"に変更して保存 - ファイル名を日付付きにして自動でバージョン管理
👉 これで「入力 → 集計 → CSV保存 → CSV読み込み → GUI表示 → PNG保存」まで一通りの流れが完成しました。

