- Home ›
- JFreeChartを使ったグラフ作成 ›
- グラフの出力 ›
- HERE
画像ファイルとして出力
作成したJFreeChartクラスのオブジェクトを画像ファイルとして出力する方法を確認します。ユーティリティクラスのChartUtilitiesクラスを使用します。
ChartUtilitiesクラスのクラス図は次のようになっています。
- java.lang.Object
- org.jfree.chart.ChartUtilities
- public abstract class ChartUtilities extends java.lang.Object
abstractクラスですので直接オブジェクトを作成するのではなく、用意されているスタティックメソッドを使います。
ChartUtilitiesクラスではグラフを画像データにしてストリームとして出力したり、イメージマップを出力することが可能ですがここでは画像ファイルとして保存する方法を確認します。
PNG画像として出力
PNG画像として出力するには「saveChartAsPNG」メソッドを使います。
saveChartAsPNG public static void saveChartAsPNG(java.io.File file, JFreeChart chart, int width, int height) throws java.io.IOException
Saves a chart to the specified file in PNG format. Parameters: file - the file name (null not permitted). chart - the chart (null not permitted). width - the image width. height - the image height. Throws: java.io.IOException - if there are any I/O errors.
引数には出力するファイルを表すFileクラスのオブジェクト、グラフを表すJFreeChartクラスのオブジェクト、画像の大きさを表す幅と高さの4つを指定します。
実際の使い方は次のようになります。
DefaultPieDataset data = new DefaultPieDataset(); JFreeChart chart = ChartFactory.createPieChart("Title", data, true, false, false); File file = new File("./filename.png"); try { ChartUtilities.saveChartAsPNG(file, chart, 300, 300); } catch (IOException e) { e.printStackTrace(); }
JPEG画像として出力
JPEG画像として出力するには「saveChartAsJPEG」メソッドを使います。
saveChartAsJPEG public static void saveChartAsJPEG(java.io.File file, JFreeChart chart, int width, int height) throws java.io.IOException
Saves a chart to a file in JPEG format. Parameters: file - the file (null not permitted). chart - the chart (null not permitted). width - the image width. height - the image height. Throws: java.io.IOException - if there are any I/O errors.
基本的にはPNG画像の場合と同じです。引数には出力するファイルを表すFileクラスのオブジェクト、グラフを表すJFreeChartクラスのオブジェクト、画像の大きさを表す幅と高さの4つを指定します。
実際の使い方は次のようになります。
DefaultPieDataset data = new DefaultPieDataset(); JFreeChart chart = ChartFactory.createPieChart("Title", data, true, false, false); File file = new File("./filename.jpeg"); try { ChartUtilities.saveChartAsJPEG(file, chart, 300, 300); } catch (IOException e) { e.printStackTrace(); }
サンプルプログラム
では簡単なサンプルを作成して試してみます。
import org.jfree.chart.JFreeChart; import org.jfree.chart.ChartFactory; import org.jfree.data.general.DefaultPieDataset; import org.jfree.chart.ChartUtilities; import java.io.File; import java.io.IOException; public class Test1_1{ public static void main(String[] args) { DefaultPieDataset data = new DefaultPieDataset(); data.setValue("1個", 20); data.setValue("2個", 45); data.setValue("3個", 10); data.setValue("4個", 8); data.setValue("その他", 17); JFreeChart chart = ChartFactory.createPieChart("金メダル予想", data, true, false, false); File file = new File("./test1_1.jpeg"); try { ChartUtilities.saveChartAsJPEG(file, chart, 400, 300); } catch (IOException e) { e.printStackTrace(); } } }
上記をコンパイルした後で実行すると次のように表示されます。
実行後下記のJPEG画像が出力されています。
( Written by Tatsuo Ikura )