Example usage for org.jfree.chart ChartUtilities saveChartAsPNG

List of usage examples for org.jfree.chart ChartUtilities saveChartAsPNG

Introduction

In this page you can find the example usage for org.jfree.chart ChartUtilities saveChartAsPNG.

Prototype

public static void saveChartAsPNG(File file, JFreeChart chart, int width, int height, ChartRenderingInfo info)
        throws IOException 

Source Link

Document

Saves a chart to a file in PNG format.

Usage

From source file:com.manydesigns.portofino.pageactions.chart.jfreechart.JFreeChartInstance.java

public JFreeChartInstance(JFreeChart chart, File file, String mapId, String alt, int width, int height,
        String chartUrl) throws IOException {
    this.chart = chart;
    this.file = file;
    this.mapId = mapId;
    this.alt = alt;
    this.width = width;
    this.height = height;
    this.chartUrl = chartUrl;
    renderingInfo = new ChartRenderingInfo();
    ChartUtilities.saveChartAsPNG(file, chart, width, height, renderingInfo);
}

From source file:com.manydesigns.portofino.pageactions.chart.JFreeChartInstance.java

public JFreeChartInstance(JFreeChart chart, File file, String mapId, String alt, int width, int height,
        String chartUrl) throws IOException {
    this.chart = chart;
    this.file = file;
    this.mapId = mapId;
    this.alt = alt;
    this.width = width;
    this.height = height;
    this.chartUrl = chartUrl;
    renderingInfo = new ChartRenderingInfo();

    ChartUtilities.saveChartAsPNG(file, chart, width, height, renderingInfo);
}

From source file:utils.Graphs.java

public static File generate(File baseFolder, String titles[], int[] values, Color backgroundColor) {
    DefaultPieDataset dataset = new DefaultPieDataset();

    // add our data values
    int i = -1;//from w w w  .  j  a v a  2s.  c o m
    for (String title : titles) {
        i++;
        dataset.setValue(title, values[i]);
    }

    final JFreeChart chart =
            //                ChartFactory.createPieChart("", dataset, true, true, false);

            ChartFactory.createPieChart("", // chart title
                    dataset, // data
                    true, // include legend
                    true, false);

    PiePlot plot = (PiePlot) chart.getPlot();
    //PiePlot3D plot = (PiePlot3D) chart.getPlot();
    //plot.setStartAngle(290);
    plot.setStartAngle(45);
    plot.setDirection(Rotation.CLOCKWISE);
    plot.setForegroundAlpha(0.5f);

    //        final PiePlot plot = (PiePlot) chart.getPlot();
    plot.setBackgroundPaint(backgroundColor);

    //        plot.setLegendLabelGenerator(
    //        new StandardPieSectionLabelGenerator("{0} {2}"));

    chart.setBorderVisible(false);
    chart.getPlot().setOutlineVisible(false);
    chart.getLegend().setFrame(BlockBorder.NONE);

    // get the same background
    chart.setBackgroundPaint(backgroundColor);
    chart.getLegend().setBackgroundPaint(backgroundColor);

    // hide the shadow effects
    plot.setShadowXOffset(0);
    plot.setShadowYOffset(0);

    //chart.getLegend().setVisible(false);

    plot.setCircular(true);
    //plot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0} {2}", NumberFormat.getNumberInstance(), NumberFormat
    plot.setLabelGenerator(new StandardPieSectionLabelGenerator("{2}", NumberFormat.getNumberInstance(),
            NumberFormat.getPercentInstance()));
    plot.setNoDataMessage("No data found.");

    Color greenColor = new Color(0x8FBC0C);
    Color redColor = new Color(0xFF0000);
    //Color redColor = new Color(0xDA6022);

    plot.setSectionPaint(0, greenColor);
    plot.setSectionPaint(1, redColor);
    plot.setSectionOutlinesVisible(true);

    final ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
    final File file = new File(baseFolder, "chart.png");
    try {
        ChartUtilities.saveChartAsPNG(file, chart, 200, 160, info);
    } catch (IOException ex) {
        Logger.getLogger(Graphs.class.getName()).log(Level.SEVERE, null, ex);
    }
    //        
    ////        final ChartPanel chartPanel = new ChartPanel(chart, true);
    //       final ChartPanel chartPanel = new ChartPanel(chart, true);
    //        chartPanel.setMinimumDrawWidth(0);
    //        chartPanel.setMaximumDrawWidth(Integer.MAX_VALUE);
    //        chartPanel.setMinimumDrawHeight(0);
    //        chartPanel.setMaximumDrawHeight(Integer.MAX_VALUE);
    //        JDialog dialog = new JDialog();
    //        dialog.add(chartPanel);
    //        dialog.setLayout(new GridLayout(1, 1));
    //        dialog.setSize(400, 200);
    //        dialog.setVisible(true);

    return file;
}

From source file:org.gephi.statistics.plugin.ChartUtils.java

public static String renderChart(JFreeChart chart, String fileName) {
    String imageFile = "";
    try {/*from  w  w w  . ja  v a  2s.com*/
        final ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
        TempDir tempDir = TempDirUtils.createTempDir();
        File file1 = tempDir.createFile(fileName);
        imageFile = "<IMG SRC=\"file:" + file1.getAbsolutePath() + "\" "
                + "WIDTH=\"600\" HEIGHT=\"400\" BORDER=\"0\" USEMAP=\"#chart\"></IMG>";
        ChartUtilities.saveChartAsPNG(file1, chart, 600, 400, info);
    } catch (IOException e) {
        System.out.println(e.toString());
    }
    return imageFile;
}

From source file:org.jfree.chart.demo.ImageMapDemo6.java

/**
 * Saves the chart image and HTML.// ww  w  .  j  a  v  a2 s  .  co  m
 */
public void saveImageAndHTML() {

    final CategoryDataset dataset = createDataset();
    final JFreeChart chart = createChart(dataset);

    // ****************************************************************************
    // * JFREECHART DEVELOPER GUIDE                                               *
    // * The JFreeChart Developer Guide, written by David Gilbert, is available   *
    // * to purchase from Object Refinery Limited:                                *
    // *                                                                          *
    // * http://www.object-refinery.com/jfreechart/guide.html                     *
    // *                                                                          *
    // * Sales are used to provide funding for the JFreeChart project - please    * 
    // * support us so that we can continue developing free software.             *
    // ****************************************************************************

    // save it to an image
    try {
        final ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
        final File file1 = new File("multipiechart100.png");
        ChartUtilities.saveChartAsPNG(file1, chart, 600, 400, info);

        // write an HTML page incorporating the image with an image map
        final File file2 = new File("multipiechart100.html");
        final OutputStream out = new BufferedOutputStream(new FileOutputStream(file2));
        final PrintWriter writer = new PrintWriter(out);
        writer.println("<HTML>");
        writer.println("<HEAD><TITLE>JFreeChart Image Map Demo</TITLE></HEAD>");
        writer.println("<BODY>");
        //            ChartUtilities.writeImageMap(writer, "chart", info);
        writer.println("<IMG SRC=\"multipiechart100.png\" "
                + "WIDTH=\"600\" HEIGHT=\"400\" BORDER=\"0\" USEMAP=\"#chart\">");
        writer.println("</BODY>");
        writer.println("</HTML>");
        writer.close();

    } catch (IOException e) {
        System.out.println(e.toString());
    }
}

From source file:playground.anhorni.crossborder.verification.Verification.java

private void writeTGZMGraph() {

    int width = 800;
    int height = 600;

    for (int i = 0; i < 4; i++) {
        TGZMCompare tgzm = new TGZMCompare(this.xTripsPerHour[i], this.aggregatedVolumePerHourTGZM[i]);

        JFreeChart chart = tgzm.createChart(this.getActTypeString(i));
        String fileName = "TGZMCompare" + this.getActTypeString(i);

        try {/* w  w w. j a  v  a2 s . c  o  m*/
            ChartRenderingInfo info = null;
            info = new ChartRenderingInfo(new StandardEntityCollection());
            File file1 = new File("output/" + fileName + ".png");
            ChartUtilities.saveChartAsPNG(file1, chart, width, height, info);
        } catch (IOException e) {
            System.out.println(e.toString());
        } //catch   
    }

    int[] sumTripsPerHour = new int[24];
    double[] sumAggregatedVolumePerHour = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
            0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };

    for (int i = 0; i < 24; i++) {
        for (int j = 0; j < 4; j++) {
            sumTripsPerHour[i] += this.xTripsPerHour[j][i];
            sumAggregatedVolumePerHour[i] += this.aggregatedVolumePerHourTGZM[j][i];
        }
    }

    TGZMCompare tgzm = new TGZMCompare(sumTripsPerHour, sumAggregatedVolumePerHour);
    JFreeChart chart = tgzm.createChart("All");
    String fileName = "TGZMCompare All";

    try {
        ChartRenderingInfo info = null;
        info = new ChartRenderingInfo(new StandardEntityCollection());
        File file1 = new File("output/" + fileName + ".png");
        ChartUtilities.saveChartAsPNG(file1, chart, width, height, info);
    } catch (IOException e) {
        System.out.println(e.toString());
    } //catch
}

From source file:org.jfree.chart.demo.ImageMapDemo5.java

/**
 * Saves the chart image and HTML.//from   www . ja va2 s  . com
 */
public void saveImageAndHTML() {

    // create a dataset
    final double[][] data = new double[][] { { 56.0, -12.0, 34.0, 76.0, 56.0, 100.0, 67.0, 45.0 },
            { 37.0, 45.0, 67.0, 25.0, 34.0, 34.0, 100.0, 53.0 },
            { 43.0, 54.0, 34.0, 34.0, 87.0, 64.0, 73.0, 12.0 } };
    final CategoryDataset dataset = DatasetUtilities.createCategoryDataset("Series ", "Type ", data);

    final JFreeChart chart = createChart(dataset);

    // ****************************************************************************
    // * JFREECHART DEVELOPER GUIDE                                               *
    // * The JFreeChart Developer Guide, written by David Gilbert, is available   *
    // * to purchase from Object Refinery Limited:                                *
    // *                                                                          *
    // * http://www.object-refinery.com/jfreechart/guide.html                     *
    // *                                                                          *
    // * Sales are used to provide funding for the JFreeChart project - please    * 
    // * support us so that we can continue developing free software.             *
    // ****************************************************************************

    // save it to an image
    try {
        final ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
        final File file1 = new File("areachart100.png");
        ChartUtilities.saveChartAsPNG(file1, chart, 600, 400, info);

        // write an HTML page incorporating the image with an image map
        final File file2 = new File("areachart100.html");
        final OutputStream out = new BufferedOutputStream(new FileOutputStream(file2));
        final PrintWriter writer = new PrintWriter(out);
        writer.println("<HTML>");
        writer.println("<HEAD><TITLE>JFreeChart Image Map Demo</TITLE></HEAD>");
        writer.println("<BODY>");
        //            ChartUtilities.writeImageMap(writer, "chart", info);
        writer.println("<IMG SRC=\"areachart100.png\" "
                + "WIDTH=\"600\" HEIGHT=\"400\" BORDER=\"0\" USEMAP=\"#chart\">");
        writer.println("</BODY>");
        writer.println("</HTML>");
        writer.close();

    } catch (IOException e) {
        System.out.println(e.toString());
    }
}

From source file:org.matsim.counts.algorithms.graphs.helper.OutputDelegate.java

private void writeHtml(final CountsGraph cg, final String iter_path, boolean indexFile) {
    /* we want landscape, thus exchange width / height */
    int width = 800;
    int height = 600;

    JFreeChart chart = null;/*from w w  w.ja  v  a2  s  .  c  om*/
    String fileName = "";
    File file2;
    if (!indexFile) {
        chart = cg.getChart();
        fileName = cg.getFilename();
        file2 = new File(iter_path + "/" + fileName + ".html");
    } else {
        file2 = new File(iter_path + "/start.html");
    }

    PrintWriter writer = null;
    try {
        ChartRenderingInfo info = null;
        File file1;
        if (!indexFile) {
            info = new ChartRenderingInfo(new StandardEntityCollection());
            file1 = new File(iter_path + "/png/" + fileName + ".png");
            ChartUtilities.saveChartAsPNG(file1, chart, width, height, info);
        }

        writer = new PrintWriter(new BufferedOutputStream(new FileOutputStream(file2)));

        writer.println("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
        //writer.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">");
        writer.println(
                "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">");
        writer.println("<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\">");
        writer.println("<head>");
        //writer.println("<meta http-equiv=\"Content-Type\" content=\"application/xhtml+xml; charset=UTF-8\" />");
        writer.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />");
        writer.println("<meta http-equiv=\"Content-Script-Type\" content=\"text/javascript\"/>");
        writer.println("<meta http-equiv=\"Content-Style-Type\" content=\"text/css\"/>");

        writer.println("<title> MATSim validation </title>");
        writer.println("<script type=\"text/javascript\" src=\"div/overlib.js\"></script>");
        writer.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"div/style1.css\"/>");
        writer.println("</head>");
        writer.println("<body>");

        writer.println("<div id=\"overDiv\" style=\"Z-INDEX: 1; POSITION: absolute\"></div>");

        writer.println("<div id=\"header\">");
        writer.println("<div id=\"logo\">");
        writer.println(
                "<img src=\"div/logo.png\" width=\"224\" height=\"52\" style=\"border:none;\" alt=\"logo\"/><br>Multi-Agent Transport Simulation Toolkit");
        writer.println("</div>");
        writer.println("<h3>Counting Volumes</h3>");
        writer.println("</div>");

        writer.println("<div id=\"footer\">");

        GregorianCalendar cal = new GregorianCalendar();
        writer.println(cal.get(Calendar.DATE) + ".");
        writer.println(cal.get(Calendar.MONTH) + 1 + ".");
        writer.println(cal.get(Calendar.YEAR) + "\t ");
        writer.println(System.getProperty("user.name"));

        writer.println("</div>");
        writer.println("<div id=\"links\">");

        for (Section sec : this.sections_) {
            writer.print("<h3>");
            writer.print(sec.getTitle() + ":<br />");
            writer.print("</h3>");

            Iterator<MyURL> url_it = sec.getURLs().iterator();
            while (url_it.hasNext()) {
                MyURL url = url_it.next();
                writer.println("<a href=\"" + url.address + "\">" + url.displayText + "</a><br />");
            }
        }
        writer.println("</div>");

        writer.println("<div id=\"contents\">");
        writer.println("<p>");
        if (!indexFile) {
            ChartUtilities.writeImageMap(writer, "chart", info, true);

            /*
              chart=cg.getChart();
              CategoryPlot plot=chart.getCategoryPlot();
            Renderer renderer=(BarRenderer) plot.getRenderer();
            renderer.getSeriesToolTipGenerator(0);
             */

            /*   how to get tooltips in there, without using xxxToolTipTagFragmentGenerator?
                 Wait for next version of jFreeChart? Meanwhile doing slight changes to the libarary
                 String imagemap=ChartUtilities.getImageMap("chart", info);
                 System.out.println(imagemap);
             */

            // reference '#chart' not working without '#'
            writer.println("<img src=\"png/" + fileName + ".png\" " + "width=\"" + width + "\" height=\""
                    + height + "\" style=\"border:none;\" alt=\"graph\" usemap=\"#chart\"/>");
        } else {
            writer.println("<img src=\"div/title.png\" "
                    + "width=\"972\" height=\"602\" style=\"border:none;\" alt=\"title\"/>");
        }
        writer.println("</p>");
        writer.println("</div>");
        writer.println("</body>");
        writer.println("</html>");

    } catch (IOException e) {
        System.out.println(e.toString());
    } finally {
        if (writer != null) {
            writer.close();
        }
    }
}

From source file:action.GraphAction.java

public String drawgraph() {

    List<CustomerOrder> orderList = new ArrayList<CustomerOrder>();

    HttpServletRequest request = ServletActionContext.getRequest();
    HttpSession session = request.getSession();

    TransactionDao transactionDao = new TransactionDao();
    //  orderList = transactionDao.findByDate(fromdate, todate);
    orderList = (List<CustomerOrder>) request.getSession().getAttribute("orderList");
    int a = orderList.size();
    System.out.println("Size--->" + a);
    Number[] values = getValues(orderList);
    System.out.println("final values are " + Arrays.toString(values));

    final Number[][] data = new Number[][] { values, {} };

    final CategoryDataset dataset = DatasetUtilities.createCategoryDataset("", "", data);

    JFreeChart chart = null;//from   w  w w.  j ava 2s  .  co  m
    BarRenderer renderer3D = null;
    CategoryPlot plot = null;

    final CategoryAxis3D categoryAxis = new CategoryAxis3D("Month");
    final ValueAxis valueAxis = new NumberAxis3D("Number of Transactions");
    renderer3D = new BarRenderer3D();

    plot = new CategoryPlot(dataset, categoryAxis, valueAxis, renderer3D);
    plot.setOrientation(PlotOrientation.VERTICAL);
    chart = new JFreeChart("Online Transactions", JFreeChart.DEFAULT_TITLE_FONT, plot, true);

    chart.setBackgroundPaint(new Color(152, 169, 236));

    try {
        final ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());

        final File file1 = new File("D:\\3dbarchart.png");
        OutputStream out = ServletActionContext.getResponse().getOutputStream();
        ChartUtilities.saveChartAsPNG(file1, chart, 600, 400, info);

        ChartUtilities.writeChartAsPNG(out, chart, 600, 400, info);

        out.close();
        //returnString = "success"; 

    } catch (Exception e) {
        System.out.println(e);
        // returnString = "error";
    }
    return SUCCESS;
}

From source file:chart.statistic.HistogramChart.java

public void store(JFreeChart cp, File folder, String filename) {
    if (doStoreChart) {

        //            File folder = LogFile.folderFile;
        //            String fn = folder.getAbsolutePath() + File.separator + "images/Distribution_";
        //            File file = null;
        //            fn = fn + GeneralResultRecorder.currentSimulationLabel;

        String fn = filename;/* w w w .ja v  a 2 s .  c o m*/
        try {

            final File file1 = new File(folder.getAbsolutePath() + File.separator + fn + ".png");
            System.out
                    .println("\n>>> Save as PNG Image - Filename: " + file1.getAbsolutePath() + "; CP: " + cp);
            try {
                final ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());

                Thread.currentThread().sleep(1000);

                ChartUtilities.saveChartAsPNG(file1, chart, 600, 400, info);

                Thread.currentThread().sleep(1000);
            } catch (Exception e) {
                e.printStackTrace();
            }

            //                File file = new File(folder.getAbsolutePath() + File.separator + fn + ".svg");
            //                System.out.println(">>> Save as SVG Image - Filename: " + file.getAbsolutePath()
            //                        + "; CP: "+ cp);
            //
            //
            //                // Get a DOMImplementation and create an XML document
            //                DOMImplementation domImpl =
            //                        GenericDOMImplementation.getDOMImplementation();
            //                Document document = domImpl.createDocument(null, "svg", null);
            //
            //                // Create an instance of the SVG Generator
            //                SVGGraphics2D svgGenerator = new SVGGraphics2D(document);
            //
            //                // draw the chart in the SVG generator
            //                cp.draw(svgGenerator, new Rectangle(800, 600));
            //
            //                // Write svg file
            //                OutputStream outputStream = new FileOutputStream(file);
            //                Writer out = new OutputStreamWriter(outputStream, "UTF-8");
            //                svgGenerator.stream(out, true /* use css */);
            //                outputStream.flush();
            //                outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}