JAVA – JFreeChart – How To Save a JFreeChart to JPEG File


A quick how to use JFreeChart quide can be found at-

I wanted to be able to output the the charts to a picture file (JPEG) programatically. After a bit of research I got the following methods to paint the chart and output the image to a file.

Add these 2 methods to the class that creates the charts:

Method 1 saveToFile():

public static void saveToFile(JFreeChart chart,

    String aFileName,

    int width,

    int height,

    double quality)

    throws FileNotFoundException, IOException


        BufferedImage img = draw( chart, width, height );


        FileOutputStream fos = new FileOutputStream(aFileName);

        JPEGImageEncoder encoder2 =


        JPEGEncodeParam param2 =


        param2.setQuality((float) quality, true);





Method 2 draw():

    protected static BufferedImage draw(JFreeChart chart, int width, int height)


        BufferedImage img =

        new BufferedImage(width , height,


        Graphics2D g2 = img.createGraphics();


        chart.draw(g2, new Rectangle2D.Double(0, 0, width, height));



        return img;



Call the saveToFile method to save the chart to a JPEG:


}catch(Exception e){



This tells the application to save the current pieChart to a file called c:/test.jpg, with a width of 500 a height of 300 and a quality of 100.

The createPiePanel() method will now look like:

public static JPanel createPiePanel(int ring, int call, int off, String title) {      

        JFreeChart pieChart = createPieChart(createPieDataset(ring, call, off), title); 



        }catch(Exception e){



        return new ChartPanel(pieChart);


3 thoughts on “JAVA – JFreeChart – How To Save a JFreeChart to JPEG File

  1. If you find this page through Google (like I did), note that JFreeChart now includes functions to do this for you. They’ve likely been added since this post was written.

    Check out ChartUtilities.saveChartAsPNG (recommended) or saveChartAsJPG (if you must).

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s