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) throws IOException 

Source Link

Document

Saves a chart to the specified file in PNG format.

Usage

From source file:finalproject.FileIO.java

/**
 * Outputs the graph to a png file.//  ww w .  j  a  v a  2 s  . c o m
 * @param date
 * @param jfc
 * @throws Exception 
 */
public void saveGraph(String date, JFreeChart jfc) throws Exception {
    int width = 640; // Width of the image 
    int height = 480; // Height of the image               
    //File lineChart = new File("Resources/BGCharts/" + date + "Chart.png");

    // For "commercial" use
    /*File lineChart = new File("C:\\Program Files\\BGDataAnalysis\\BGCharts\\" 
            + date + "Chart.png");*/
    File lineChart = new File("C:\\BGDataAnalysis\\BGCharts\\" + date + "Chart.png");

    ChartUtilities.saveChartAsPNG(lineChart, jfc, width, height);

}

From source file:controle.AgController.java

public void execute() {
    long tempoInicial = System.currentTimeMillis();

    ag.run();//w  ww.  j  a v  a  2 s .  c  o m
    ChartSeries melhores = new ChartSeries();
    melhores.setLabel("Melhores");

    ChartSeries piores = new ChartSeries();
    piores.setLabel("Piores");

    ChartSeries desvioPadrao = new ChartSeries();
    desvioPadrao.setLabel("Desvio Padro");

    ChartSeries media = new ChartSeries();
    media.setLabel("Mdia");

    DefaultCategoryDataset dataset = new DefaultCategoryDataset();

    for (int i = 0; i < ag.getMelhoresIndividuos().size(); i++) {
        melhores.set(i, ag.getMelhoresIndividuos().get(i).getFitness());
        piores.set(i, ag.getPioresIndividuos().get(i).getFitness());
        desvioPadrao.set(i, ag.getDesvioPadrao().get(i));
        media.set(i, ag.getMedia().get(i));
        dataset.addValue(ag.getMelhoresIndividuos().get(i).getFitness(), "melhores", Integer.valueOf(i));

    }
    model.addSeries(melhores);
    model.addSeries(piores);
    model.addSeries(desvioPadrao);
    model.addSeries(media);
    model.setTitle("Desempenho por Geraes");
    model.setLegendPosition("e"); //nw
    model.setAnimate(true);
    model.setSeriesColors("00cc00,cc0000,e5e55f,0099ff");

    try {
        JFreeChart jfreechart = ChartFactory.createLineChart("Melhores", "Geraes", "Fitness", dataset);
        File chartFile = new File("dynamichart");
        ChartUtilities.saveChartAsPNG(chartFile, jfreechart, 600, 400);
        chart = new DefaultStreamedContent(new FileInputStream(chartFile), "image/png");
    } catch (Exception e) {
        e.printStackTrace();
    }

    long tempoFinal = System.currentTimeMillis();
    tempoExecucao = (tempoFinal - tempoInicial) / 1000;

}

From source file:org.encog.workbench.util.graph.EncogChartPanel.java

/**
 * Opens a file chooser and gives the user an opportunity to save the chart
 * in PNG format./*from  w  w w . j  a  va2 s. c  o m*/
 *
 * @throws IOException if there is an I/O error.
 */
public void doSaveAs() throws IOException {

    SaveImageDialog dialog = new SaveImageDialog(EncogWorkBench.getInstance().getMainWindow());

    dialog.getImageWidth().setValue(640);
    dialog.getImageHeight().setValue(480);

    if (dialog.process()) {

        File filename = new File(dialog.getTargetFile().getValue());
        int width = dialog.getImageWidth().getValue();
        int height = dialog.getImageHeight().getValue();

        switch (dialog.getFileType().getSelectedIndex()) {
        case 0:
            filename = new File(FileUtil.forceExtension(filename.toString(), "png"));
            ChartUtilities.saveChartAsPNG(filename, this.getChart(), width, height);
            break;
        case 1:
            filename = new File(FileUtil.forceExtension(filename.toString(), "jpg"));
            ChartUtilities.saveChartAsPNG(filename, this.getChart(), width, height);
            break;
        case 2:
            filename = new File(FileUtil.forceExtension(filename.toString(), "pdf"));
            DocumentPDF.savePDF(filename, getChart(), width, height);
            break;
        case 3:
            filename = new File(FileUtil.forceExtension(filename.toString(), "svg"));
            DocumentSVG.saveSVG(filename, getChart(), width, height);
            break;

        }
    }

}

From source file:de.dfki.owlsmx.gui.ShowResultVisualization.java

private void saveActionPerformed(java.awt.event.ActionEvent event) {//GEN-FIRST:event_saveActionPerformed
    try {/* w ww.ja  va 2s.c  om*/
        if (event.getSource().equals(save)) {
            if (fc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
                if (fc.getFileFilter().getClass().equals((new PNGFilter()).getClass()))
                    if (fc.getSelectedFile().getAbsolutePath().toLowerCase().endsWith(".png"))
                        ChartUtilities.saveChartAsPNG(fc.getSelectedFile(), chart,
                                ResultVisualization.graphPrintWidth, ResultVisualization.graphPrintHeight);
                    else
                        ChartUtilities.saveChartAsPNG(new File(fc.getSelectedFile().getAbsolutePath() + ".png"),
                                chart, ResultVisualization.graphPrintWidth,
                                ResultVisualization.graphPrintHeight);

                else if (fc.getFileFilter().getClass().equals((new JPGFilter()).getClass()))
                    if (fc.getSelectedFile().getAbsolutePath().toLowerCase().endsWith(".png"))
                        ChartUtilities.saveChartAsJPEG(fc.getSelectedFile(), chart,
                                ResultVisualization.graphPrintWidth, ResultVisualization.graphPrintHeight);
                    else
                        ChartUtilities.saveChartAsJPEG(
                                new File(fc.getSelectedFile().getAbsolutePath() + ".png"), chart,
                                ResultVisualization.graphPrintWidth, ResultVisualization.graphPrintHeight);

                else if (fc.getFileFilter().getClass().equals((new PDFFilter()).getClass()))
                    if (fc.getSelectedFile().getAbsolutePath().toLowerCase().endsWith(".pdf"))
                        Converter.convertToPdf(chart, ResultVisualization.graphPrintWidth,
                                ResultVisualization.graphPrintHeight, fc.getSelectedFile().getAbsolutePath());
                    else
                        Converter.convertToPdf(chart, ResultVisualization.graphPrintWidth,
                                ResultVisualization.graphPrintHeight,
                                fc.getSelectedFile().getAbsolutePath() + ".pdf");
                else if (fc.getFileFilter().getClass().equals((new EPSFilter()).getClass()))
                    printGraphics2DtoEPS(fc.getSelectedFile().getAbsolutePath());
            }
        }
    } catch (Exception e) {
        GUIState.displayWarning(e.getClass().toString(),
                "Couldn't save file " + fc.getSelectedFile().getAbsolutePath());
        e.printStackTrace();
    }
}

From source file:org.miloss.fgsms.services.rs.impl.reports.broker.QueueTopicCountByBroker.java

@Override
public void generateReport(OutputStreamWriter data, List<String> urls, String path, List<String> files,
        TimeRange range, String currentuser, SecurityWrapper classification, WebServiceContext ctx)
        throws IOException {

    Connection con = Utility.getPerformanceDBConnection();
    try {//from ww  w  . j av  a  2  s .  c om
        PreparedStatement cmd = null;
        ResultSet rs = null;
        DefaultCategoryDataset set = new DefaultCategoryDataset();
        JFreeChart chart = null;

        data.append("<hr /><h2>").append(GetDisplayName()).append("</h2>");
        data.append(GetHtmlFormattedHelp() + "<br />");
        data.append("<table class=\"table table-hover\"><tr><th>URI</th><th>Channel Count</th></tr>");

        for (int i = 0; i < urls.size(); i++) {
            if (!isPolicyTypeOf(urls.get(i), PolicyType.STATISTICAL)) {
                continue;
            }
            //https://github.com/mil-oss/fgsms/issues/112
            if (!UserIdentityUtil.hasReadAccess(currentuser, "getReport", urls.get(i), classification, ctx)) {
                continue;
            }
            String url = Utility.encodeHTML(getPolicyDisplayName(urls.get(i)));
            data.append("<tr><td>").append(url).append("</td>");
            long count = 0;
            try {

                //FIXME could this be simplified?
                cmd = con.prepareStatement(
                        "select canonicalname from brokerhistory where host=?  group by canonicalname;");
                cmd.setString(1, urls.get(i));
                rs = cmd.executeQuery();
                if (rs.next()) {
                    count++;
                }

            } catch (Exception ex) {
                log.log(Level.ERROR, "Error opening or querying the database.", ex);
            } finally {
                DBUtils.safeClose(rs);
                DBUtils.safeClose(cmd);
            }
            data.append("<td>").append(count + "").append("</td></tr>");
            set.addValue(count, urls.get(i), urls.get(i));

        }
        data.append("</table>");

        chart = org.jfree.chart.ChartFactory.createBarChart(GetDisplayName(), "Service URL", "", set,
                PlotOrientation.HORIZONTAL, true, false, false);

        try {
            //  if (set.getRowCount() != 0) {
            ChartUtilities.saveChartAsPNG(new File(
                    path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png"), chart,
                    1500, pixelHeightCalc(set.getRowCount()));
            data.append("<img src=\"image_").append(this.getClass().getSimpleName()).append(".png\">");
            files.add(path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png");
            // }
        } catch (IOException ex) {
            log.log(Level.ERROR, "Error saving chart image for request", ex);
        }
    } catch (Exception ex) {
        log.log(Level.ERROR, null, ex);
    } finally {
        DBUtils.safeClose(con);
    }
}

From source file:org.miloss.fgsms.services.rs.impl.reports.ws.InvocationsByServiceByMethod.java

@Override
public void generateReport(OutputStreamWriter data, List<String> urls, String path, List<String> files,
        TimeRange range, String currentuser, SecurityWrapper classification, WebServiceContext ctx)
        throws IOException {

    Connection con = Utility.getPerformanceDBConnection();
    try {/* w  ww .  j  av  a 2  s. com*/
        PreparedStatement cmd = null;
        ResultSet rs = null;
        DefaultCategoryDataset set = new DefaultCategoryDataset();
        JFreeChart chart = null;

        data.append("<hr /><h2>").append(GetDisplayName()).append("</h2>");
        data.append("This represents the invocations for each service by method (action).<br />");
        data.append(
                "<table class=\"table table-hover\"><tr><th>URL</th><th>Action</th><th>Invocations</th></tr>");
        for (int i = 0; i < urls.size(); i++) {
            if (!isPolicyTypeOf(urls.get(i), PolicyType.TRANSACTIONAL)) {
                continue;
            }
            //https://github.com/mil-oss/fgsms/issues/112
            if (!UserIdentityUtil.hasReadAccess(currentuser, "getReport", urls.get(i), classification, ctx)) {
                continue;
            }
            String url = Utility.encodeHTML(BaseReportGenerator.getPolicyDisplayName(urls.get(i)));
            List<String> actions = getSoapActions(urls.get(i), con);

            for (int k = 0; k < actions.size(); k++) {

                long count = 0;
                try {
                    cmd = con.prepareStatement("select count(*) from RawData where URI=? and "
                            + "(UTCdatetime > ?) and (UTCdatetime < ?) and soapaction=?;");
                    cmd.setString(1, urls.get(i));
                    cmd.setLong(2, range.getStart().getTimeInMillis());
                    cmd.setLong(3, range.getEnd().getTimeInMillis());
                    cmd.setString(4, actions.get(k));

                    rs = cmd.executeQuery();

                    if (rs.next()) {
                        count = rs.getLong(1);
                    }

                } catch (Exception ex) {
                    log.log(Level.WARN, null, ex);
                } finally {
                    DBUtils.safeClose(rs);
                    DBUtils.safeClose(cmd);
                }

                data.append("<tr><td>").append(url).append("</td><td>");
                data.append(Utility.encodeHTML(actions.get(k))).append("</td><td>").append(count + "")
                        .append("</td></tr>");
                if (count > 0) {
                    set.addValue(count, actions.get(k), url);
                }
            }
        }
        data.append("</table>");
        chart = org.jfree.chart.ChartFactory.createBarChart(GetDisplayName(), "Service URL", "", set,
                PlotOrientation.HORIZONTAL, true, false, false);

        try {
            ChartUtilities.saveChartAsPNG(new File(
                    path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png"), chart,
                    1500, pixelHeightCalc(set.getRowCount()));
        } catch (IOException ex) {
            log.log(Level.ERROR, "Error saving chart image for request", ex);
        }

        data.append("<img src=\"image_").append(this.getClass().getSimpleName()).append(".png\">");
        files.add(path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png");
    } catch (Exception ex) {
        log.log(Level.ERROR, null, ex);
    } finally {
        DBUtils.safeClose(con);
    }
}

From source file:edu.gcsc.vrl.jfreechart.JFExport.java

/**
 * Export jfreechart to image format. File must have an extension like jpg,
 * png, pdf, svg, eps. Otherwise export will fail.
 *
 * @param file Destination Filedescriptor
 * @param chart JFreechart//w  w  w  .j  av a  2  s  .c o m
 * @throws Exception
 */
public boolean export(File file, JFreeChart chart) throws Exception {

    /*Get extension from file - File must have one extension of
     jpg,png,pdf,svg,eps. Otherwise the export will fail.
     */
    String ext = JFUtils.getExtension(file);

    //  TODO - Make x,y variable
    int x, y;
    // Set size for image (jpg)
    x = 550;
    y = 470;

    int found = 0;

    // JPEG
    if (ext.equalsIgnoreCase("jpg")) {
        ChartUtilities.saveChartAsJPEG(file, chart, x, y);
        found++;
    }
    // PNG
    if (ext.equalsIgnoreCase("png")) {
        ChartUtilities.saveChartAsPNG(file, chart, x, y);
        found++;
    }

    // PDF
    if (ext.equalsIgnoreCase("pdf")) {

        //JRAbstractRenderer jfcRenderer = new JFreeChartRenderer(chart);
        // Use here size of r2d2 (see below, Rectangel replaced by Rectangle2D !)
        Rectangle pagesize = new Rectangle(x, y);

        Document document = new Document(pagesize, 50, 50, 50, 50);
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
        document.open();
        PdfContentByte cb = writer.getDirectContent();
        PdfTemplate tp = cb.createTemplate(x, y);

        Graphics2D g2 = tp.createGraphics(x, y, new DefaultFontMapper());

        // Draw doesn't works with Rectangle argument - use rectangle2D instead !
        //chart.draw(g2, (java.awt.geom.Rectangle2D) new Rectangle(x,y));
        Rectangle2D r2d2 = new Rectangle2D.Double(0, 0, x, y);
        chart.draw(g2, r2d2);

        g2.dispose();
        cb.addTemplate(tp, 0, 0);
        document.close();

        found++;

    }

    // SVG
    if (ext.equalsIgnoreCase("svg")) {
        // When exporting to SVG don't forget this VERY important line:
        // svgGenerator.setSVGCanvasSize(new Dimension(width, height));
        // Otherwise renderers will not know the size of the image. It will be drawn to the correct rectangle, but the image will not have a correct default siz
        // Get a DOMImplementation
        DOMImplementation domImpl = SVGDOMImplementation.getDOMImplementation();
        org.w3c.dom.Document document = domImpl.createDocument(null, "svg", null);
        SVGGraphics2D svgGenerator = new SVGGraphics2D(document);
        //chart.draw(svgGenerator,new Rectangle(x,y));
        chart.draw(svgGenerator, new Rectangle2D.Double(0, 0, x, y));

        boolean useCSS = true; // we want to use CSS style attribute

        Writer out = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
        svgGenerator.stream(out, useCSS);
        out.close();
        found++;
    }

    if (ext.equalsIgnoreCase("eps")) {

        //Graphics2D g = new EpsGraphics2D();
        FileOutputStream out = new FileOutputStream(file);
        //Writer out=new FileWriter(file);
        Graphics2D g = new EpsGraphics(file.getName(), out, 0, 0, x, y, ColorMode.COLOR_RGB);

        chart.draw(g, new Rectangle2D.Double(0, 0, x, y));
        //Writer out=new FileWriter(file);
        out.write(g.toString().getBytes());
        out.close();
        found++;
    }

    if (found == 0) {
        throw new IllegalArgumentException("File format '" + ext + "' not supported!");
    }

    return true;

}

From source file:org.matsim.contrib.socnetsim.usage.analysis.CourtesyHistogramListener.java

public static void writeGraphic(CourtesyHistogram courtesyHistogram, final String actType,
        final String filename) {
    try {//  w  w w  .  j  av  a2 s .co m
        ChartUtilities.saveChartAsPNG(new File(filename),
                getGraphic(courtesyHistogram.getDataFrames().get(actType), courtesyHistogram.getIteration(),
                        actType),
                1024, 768);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}

From source file:correospingtelnet.CorreosPingTelnet.java

private void mainAnterior() throws Exception {
    //JFreeChart chart; 
    //chart = createPlot();         
    //ChartUtilities.saveChartAsPNG(new File("imagen.png"), chart, 1000, 600);

    // request/*from www .  ja  va2  s . c om*/
    final IcmpPingRequest request = IcmpPingUtil.createIcmpPingRequest();
    request.setHost("192.168.1.5");

    final XYSeries google = new XYSeries("Ping a google");
    // repeat a few times
    for (int count = 1; count <= 1; count++) {

        // delegate
        final IcmpPingResponse response = IcmpPingUtil.executePingRequest(request);

        // log
        final String formattedResponse = IcmpPingUtil.formatResponse(response);
        System.out.println(formattedResponse);
        //Aqu tomaremos el valor de los ms y los guardaremos en un arreglo. 
        String[] splitStr = formattedResponse.split("\\s+");
        int valor = 0;
        if (splitStr.length > 5) {
            //Quitamos los ms
            char[] cadenaEnChars = splitStr[4].toCharArray();
            if (cadenaEnChars.length == 8) {
                valor = Integer.parseInt(Character.toString(cadenaEnChars[5]));
            } else {
                valor = Integer
                        .parseInt(Character.toString(cadenaEnChars[5]) + Character.toString(cadenaEnChars[6]));
            }

        } else {
            //Aqu hacer telnet
            //Aqu enviar correo             
            Telnet.doTelnet("64.62.142.154");
            valor = 0;
        }

        google.add(count, valor);

        // rest
        Thread.sleep(1000);
    }

    final XYSeriesCollection dataset = new XYSeriesCollection();
    dataset.addSeries(google);

    JFreeChart xylineChart = ChartFactory.createXYLineChart("Grfica de ping", "Ping #", "ms", dataset,
            PlotOrientation.VERTICAL, true, true, false);

    ChartUtilities.saveChartAsPNG(new File("imagen.png"), xylineChart, 1000, 600);
}

From source file:edu.uara.tableeditor.TableFigure.java

public void compileFigure(String path) {
    try {//from w  ww.j  a v  a 2s .c  o  m

        File chartFile = new File(path + "Chart_" + this.title + ".png");
        ChartUtilities.saveChartAsPNG(chartFile, chart.getChart(), this.figureSize.width,
                this.figureSize.height);
    } catch (Exception ex) {
        System.out.println("Error compiling figure: " + this.title + ". " + ex.getMessage());

    }
}