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.qspin.qtaste.reporter.testresults.html.HTMLReportFormatter.java

private void generatePieChart() {
    if (currentTestSuite == null) {
        return;//from w w  w .j a v a  2 s  .co  m
    }

    File testSummaryFile = new File(reportFile.getParentFile(), testSummaryFileName);
    File tempTestSummaryFile = new File(testSummaryFile.getPath() + ".tmp");

    final DefaultPieDataset pieDataSet = new DefaultPieDataset();

    pieDataSet.setValue("Passed", new Integer(currentTestSuite.getNbTestsPassed()));
    pieDataSet.setValue("Failed", new Integer(currentTestSuite.getNbTestsFailed()));
    pieDataSet.setValue("Tests in error", new Integer(currentTestSuite.getNbTestsNotAvailable()));
    pieDataSet.setValue("Not executed",
            new Integer(currentTestSuite.getNbTestsToExecute() - currentTestSuite.getNbTestsExecuted()));
    JFreeChart chart = null;
    final boolean drilldown = true;

    // create the chart...
    if (drilldown) {
        final PiePlot plot = new PiePlot(pieDataSet);

        Color[] colors = { new Color(100, 230, 40), new Color(210, 35, 35), new Color(230, 210, 40),
                new Color(100, 90, 40) };
        PieRenderer renderer = new PieRenderer(colors);
        renderer.setColor(plot, (DefaultPieDataset) pieDataSet);

        plot.setURLGenerator(new StandardPieURLGenerator("pie_chart_detail.jsp"));
        plot.setLabelGenerator(new TestSectiontLabelPieGenerator());
        chart = new JFreeChart("Test summary", JFreeChart.DEFAULT_TITLE_FONT, plot, true);
    } else {
        chart = ChartFactory.createPieChart("Test summary", // chart title
                pieDataSet, // data
                true, // include legend
                true, false);
    }

    chart.setBackgroundPaint(java.awt.Color.white);

    try {
        final ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
        ChartUtilities.saveChartAsPNG(tempTestSummaryFile, chart, 600, 400, info);
    } catch (IOException e) {
        logger.error("Problem saving png chart", e);
    }

    testSummaryFile.delete();
    if (!tempTestSummaryFile.renameTo(testSummaryFile)) {
        logger.error("Couldn't rename test summary file " + tempTestSummaryFile + " into " + testSummaryFile);
    }
}

From source file:org.apache.hadoopts.app.bucketanalyser.TSOperationControlerPanel.java

public void storeChartImageAsPNG(JFreeChart chart, File folder, String filename) {

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

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

            Thread.currentThread().sleep(1000);

            ChartUtilities.saveChartAsPNG(file1, chart, 800, 600, 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();
    }
}

From source file:UserInfo_Frame.java

private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed
    String pressure = txt_pressure.getText();
    String temperature = txt_temperature.getText();
    String volumeflow = txt_volume.getText();
    String rotationalSpeed = txt_rotationalSpd.getText();

    DefaultPieDataset pieDataset = new DefaultPieDataset();

    pieDataset.setValue("Pressure", new Double(pressure));
    pieDataset.setValue("Temperature", new Double(temperature));
    pieDataset.setValue("Volume Flow", new Double(volumeflow));
    pieDataset.setValue("Rotational Speeed", new Double(rotationalSpeed));

    //JFreeChart chart = ChartFactory.createPieChart("Pie Chart",pieDataset,true,true,true); // create normal piechart
    //PiePlot3D p = (PiePlot)chart.getPlot();
    JFreeChart chart = ChartFactory.createPieChart3D("Parameter Pie Chart", pieDataset, true, true, true);// create 3D piechart
    PiePlot3D p = (PiePlot3D) chart.getPlot();
    //p.setForegroundAlpha(TOP_ALIGNMENT);
    ChartFrame cframe = new ChartFrame("Pie Chart", chart);
    cframe.setVisible(true);/*from  w w w.  j a va  2  s . co  m*/
    cframe.setSize(450, 500);
    try {
        //save chart as PNG
        final ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
        final File file1 = new File("chart.png");
        ChartUtilities.saveChartAsPNG(file1, chart, 600, 400, info);
    } catch (Exception e) {

    }

}

From source file:servlets.LeasingControllerServlet.java

public void doGetChart() {
    PieDataset pieDataset = createDataset();
    JFreeChart chart = ChartFactory.createPieChart("Tenant Mix ", pieDataset, true, true, false);
    //chart.setBackgroundPaint(new Color(222, 222, 255));
    final PiePlot plot = (PiePlot) chart.getPlot();
    plot.setBackgroundPaint(Color.white);
    plot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0} {2}"));
    plot.setCircular(true);/*  ww  w  . j  a va2 s.  c  o  m*/
    plot.setSectionPaint("F&B", new Color(15, 192, 252));
    try {
        final ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
        final File file1 = new File(
                getServletContext().getRealPath("") + "/leasingSystem/leasingSystemAssets/chart/piechart.png");
        ChartUtilities.saveChartAsPNG(file1, chart, 600, 400, info);
    } catch (Exception e) {
        System.out.println(e);

    }
}

From source file:it.eng.spagobi.kpi.utils.BasicTemplateBuilder.java

private SourceBean setLineAttributes(KpiLine line, SourceBean semaphor, SourceBean textCodeName,
        SourceBean textValue, SourceBean textWeight, SourceBean image1, int level, SourceBean separatorline,
        SourceBean threshCode, SourceBean threshValue, SourceBean extraimageToAdd) {
    logger.debug("IN");

    KpiValue kpiValue = line.getValue();

    ThresholdValue t = null;//  w ww  .j a  v a 2 s  .  c  om
    Color colorSemaphor = null;
    if (kpiValue != null && kpiValue.getValue() != null) {
        t = kpiValue.getThresholdOfValue();
        if (t != null) {
            colorSemaphor = t.getColor();
        }
    }

    Integer xValue = xStarter + (xIncrease * Integer.valueOf(level));
    Integer yValue = actualHeight;

    try {
        //set Semaphor
        semaphor.setAttribute("reportElement.x", xValue.toString());
        semaphor.setAttribute("reportElement.y", new Integer(yValue.intValue() + 2).toString());
        if (colorSemaphor != null) {

            String color = Integer.toHexString(colorSemaphor.getRGB());
            color = "#" + color.substring(2);

            semaphor.setAttribute("reportElement.forecolor", "#000000");
            semaphor.setAttribute("reportElement.backcolor", color);
        } else {
            semaphor.setAttribute("reportElement.forecolor", "#FFFFFF");
            semaphor.setAttribute("reportElement.backcolor", "#FFFFFF");
        }
        xValue = xValue + semaphorWidth + separatorWidth;

        // set text 1: Model CODE - Model NAME
        textCodeName.setAttribute("reportElement.x", (xValue));
        textCodeName.setAttribute("reportElement.y", yValue.toString());
        SourceBean textValue1 = (SourceBean) textCodeName.getAttribute("text");
        textValue1.setCharacters(line.getModelInstanceCode() + "-" + line.getModelNodeName());

        xValue = xValue + textWidth + separatorWidth;

        //Set Value, weight and threshold code and value
        if (kpiValue != null) {
            String value1 = kpiValue.getValue() != null ? kpiValue.getValue() : "";
            //set text2
            textValue.setAttribute("reportElement.y", yValue.toString());
            SourceBean textValue2 = (SourceBean) textValue.getAttribute("text");
            textValue2.setCharacters(value1);

            String weight = (kpiValue.getWeight() != null) ? kpiValue.getWeight().toString() : "";
            //set text2
            xValue = xValue + numbersWidth + separatorWidth;
            textWeight.setAttribute("reportElement.y", new Integer(yValue.intValue() + 2).toString());
            SourceBean textValue3 = (SourceBean) textWeight.getAttribute("text");
            textValue3.setCharacters(weight);

            if (t != null) {
                try {
                    Threshold tr = DAOFactory.getThresholdDAO().loadThresholdById(t.getThresholdId());
                    if (!thresholdsList.contains(tr)) {
                        thresholdsList.add(tr);
                    }

                } catch (EMFUserError e) {
                    logger.error("error in loading the Threshold by Id", e);
                    e.printStackTrace();
                }
                String code = t.getThresholdCode() != null ? t.getThresholdCode() : "";
                String codeTh = "Code: " + code;
                if (codeTh.length() > 20)
                    codeTh = codeTh.substring(0, 19);

                threshCode.setAttribute("reportElement.y", new Integer(yValue.intValue() - 2).toString());
                SourceBean threshCode2 = (SourceBean) threshCode.getAttribute("text");
                threshCode2.setCharacters(codeTh);

                String labelTh = t.getLabel() != null ? t.getLabel() : "";
                String min = t.getMinValue() != null ? t.getMinValue().toString() : null;
                String max = t.getMaxValue() != null ? t.getMaxValue().toString() : null;
                String valueTh = "Value: ";
                if (t.getThresholdType().equalsIgnoreCase("RANGE")) {
                    if (min != null && max != null) {
                        valueTh = valueTh + min + "-" + max + " " + labelTh;
                    } else if (min != null && max == null) {
                        valueTh = valueTh + "> " + min + " " + labelTh;
                    } else if (min == null && max != null) {
                        valueTh = valueTh + "< " + max + " " + labelTh;
                    }
                } else if (t.getThresholdType().equalsIgnoreCase("MINIMUM")) {
                    valueTh = valueTh + "< " + min + " " + labelTh;
                } else if (t.getThresholdType().equalsIgnoreCase("MAXIMUM")) {
                    valueTh = valueTh + "> " + max + " " + labelTh;
                }
                if (valueTh.length() > 25)
                    valueTh = valueTh.substring(0, 24);

                threshValue.setAttribute("reportElement.y", new Integer(yValue.intValue() + 7).toString());
                SourceBean threshValue2 = (SourceBean) threshValue.getAttribute("text");
                threshValue2.setCharacters(valueTh);
            }

        }
        //Sets the bullet chart and or the threshold image
        if (options.getDisplay_bullet_chart() && options.getDisplay_threshold_image()) {
            //both threshold image and bullet chart have to be seen
            if (kpiValue != null && kpiValue.getValue() != null && kpiValue.getThresholdValues() != null
                    && !kpiValue.getThresholdValues().isEmpty()) {

                List thresholdValues = kpiValue.getThresholdValues();
                // String chartType = value.getChartType(); 
                String chartType = "BulletGraph";
                Double val = new Double(kpiValue.getValue());
                Double target = kpiValue.getTarget();
                ChartImpl sbi = ChartImpl.createChart(chartType);
                sbi.setValueDataSet(val);
                if (target != null) {
                    sbi.setTarget(target);
                }
                sbi.setShowAxis(options.getShow_axis());
                sbi.setThresholdValues(thresholdValues);

                JFreeChart chart = sbi.createChart();
                ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
                String requestIdentity = null;
                UUIDGenerator uuidGen = UUIDGenerator.getInstance();
                UUID uuid = uuidGen.generateTimeBasedUUID();
                requestIdentity = uuid.toString();
                requestIdentity = requestIdentity.replaceAll("-", "");
                String path_param = requestIdentity;
                String dir = System.getProperty("java.io.tmpdir");
                String path = dir + "/" + requestIdentity + ".png";
                java.io.File file1 = new java.io.File(path);
                logger.debug("Where is the image: " + path);
                try {
                    ChartUtilities.saveChartAsPNG(file1, chart, 89, 11, info);
                } catch (IOException e) {
                    e.printStackTrace();
                    logger.error("Error in saving chart", e);
                }
                String urlPng = GeneralUtilities.getSpagoBiHost() + GeneralUtilities.getSpagoBiContext()
                        + GeneralUtilities.getSpagoAdapterHttpUrl()
                        + "?ACTION_NAME=GET_PNG2&NEW_SESSION=TRUE&path=" + path_param
                        + "&LIGHT_NAVIGATOR_DISABLED=TRUE";
                urlPng = "new java.net.URL(\"" + urlPng + "\")";
                logger.debug("Image url: " + urlPng);

                image1.setAttribute("reportElement.y", yValue.toString());
                image1.setAttribute("reportElement.x", new Integer(310).toString());
                image1.setAttribute("reportElement.width", 90);
                SourceBean imageValue = (SourceBean) image1.getAttribute("imageExpression");
                imageValue.setCharacters(urlPng);
            }
            ThresholdValue tOfVal = line.getThresholdOfValue();
            if (tOfVal != null && tOfVal.getPosition() != null && tOfVal.getThresholdCode() != null) {
                String fileName = "position_" + tOfVal.getPosition().intValue();
                String dirName = tOfVal.getThresholdCode();
                String urlPng = GeneralUtilities.getSpagoBiHost() + GeneralUtilities.getSpagoBiContext()
                        + GeneralUtilities.getSpagoAdapterHttpUrl()
                        + "?ACTION_NAME=GET_THR_IMAGE&NEW_SESSION=TRUE&fileName=" + fileName + "&dirName="
                        + dirName + "&LIGHT_NAVIGATOR_DISABLED=TRUE";

                urlPng = "new java.net.URL(\"" + urlPng + "\")";
                logger.debug("url: " + urlPng);

                extraimageToAdd = new SourceBean(image);
                extraimageToAdd.setAttribute("reportElement.y", yValue.toString());
                extraimageToAdd.setAttribute("reportElement.width", 35);
                extraimageToAdd.setAttribute("reportElement.x", new Integer(408).toString());
                SourceBean imageValue = (SourceBean) extraimageToAdd.getAttribute("imageExpression");
                imageValue.setCharacters(urlPng);
            }
        } else if (options.getDisplay_bullet_chart() && !options.getDisplay_threshold_image()) {
            //only bullet chart has to be seen
            if (kpiValue != null && kpiValue.getValue() != null && kpiValue.getThresholdValues() != null
                    && !kpiValue.getThresholdValues().isEmpty()) {

                List thresholdValues = kpiValue.getThresholdValues();
                // String chartType = value.getChartType(); 
                String chartType = "BulletGraph";
                Double val = new Double(kpiValue.getValue());
                Double target = kpiValue.getTarget();
                ChartImpl sbi = ChartImpl.createChart(chartType);
                sbi.setValueDataSet(val);
                if (target != null) {
                    sbi.setTarget(target);
                }
                sbi.setShowAxis(options.getShow_axis());
                sbi.setThresholdValues(thresholdValues);

                JFreeChart chart = sbi.createChart();
                ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
                String requestIdentity = null;
                UUIDGenerator uuidGen = UUIDGenerator.getInstance();
                UUID uuid = uuidGen.generateTimeBasedUUID();
                requestIdentity = uuid.toString();
                requestIdentity = requestIdentity.replaceAll("-", "");
                String path_param = requestIdentity;
                String dir = System.getProperty("java.io.tmpdir");
                String path = dir + "/" + requestIdentity + ".png";
                java.io.File file1 = new java.io.File(path);
                logger.debug("Where is the image: " + path);
                try {
                    ChartUtilities.saveChartAsPNG(file1, chart, 130, 11, info);
                } catch (IOException e) {
                    e.printStackTrace();
                    logger.error("Error in saving chart", e);
                }
                String urlPng = GeneralUtilities.getSpagoBiHost() + GeneralUtilities.getSpagoBiContext()
                        + GeneralUtilities.getSpagoAdapterHttpUrl()
                        + "?ACTION_NAME=GET_PNG2&NEW_SESSION=TRUE&path=" + path_param
                        + "&LIGHT_NAVIGATOR_DISABLED=TRUE";
                urlPng = "new java.net.URL(\"" + urlPng + "\")";
                logger.debug("Image url: " + urlPng);

                image1.setAttribute("reportElement.y", yValue.toString());
                SourceBean imageValue = (SourceBean) image1.getAttribute("imageExpression");
                imageValue.setCharacters(urlPng);
            }
        } else if (!options.getDisplay_bullet_chart() && options.getDisplay_threshold_image()) {
            //only threshold image has to be seen
            ThresholdValue tOfVal = line.getThresholdOfValue();
            if (tOfVal != null && tOfVal.getPosition() != null && tOfVal.getThresholdCode() != null) {
                String fileName = "position_" + tOfVal.getPosition().intValue();
                String dirName = tOfVal.getThresholdCode();
                String urlPng = GeneralUtilities.getSpagoBiHost() + GeneralUtilities.getSpagoBiContext()
                        + GeneralUtilities.getSpagoAdapterHttpUrl()
                        + "?ACTION_NAME=GET_THR_IMAGE&NEW_SESSION=TRUE&fileName=" + fileName + "&dirName="
                        + dirName + "&LIGHT_NAVIGATOR_DISABLED=TRUE";

                urlPng = "new java.net.URL(\"" + urlPng + "\")";
                logger.debug("url: " + urlPng);
                image1.setAttribute("reportElement.y", yValue.toString());
                SourceBean imageValue = (SourceBean) image1.getAttribute("imageExpression");
                imageValue.setCharacters(urlPng);

            }
        }

        separatorline.setAttribute("reportElement.y", new Integer(yValue.intValue() + 16).toString());

    } catch (SourceBeanException e) {
        logger.error("error in drawing the line", e);
        e.printStackTrace();
    }
    logger.debug("OUT");
    return extraimageToAdd;
}

From source file:org.pentaho.platform.uifoundation.chart.JFreeChartEngine.java

/**
 * Create a PNG image file from a JFreeChart object
 * //from w  w  w .j  a  v a 2 s .  c  om
 * @param chart
 *          The chart object to create an image from
 * @param path
 *          The path and name of the image file to create
 * @param width
 *          The width of the image in pixels
 * @param height
 *          The height of the image in pixels
 * @param writer
 *          A writer for the iamge map to be written to
 * @throws IOException
 */
private static void saveChartAsPNG(final JFreeChart chart, final String path, final int width, final int height,
        final PrintWriter writer, final ChartRenderingInfo info) throws IOException {
    File file = new File(path + ".png"); //$NON-NLS-1$
    ChartUtilities.saveChartAsPNG(file, chart, width, height, info);

    // TODO support tool tip generators

    // TODO support URL fragment generators

    // TODO: make the image map name unique on the page
    if (writer != null) {
        ChartUtilities.writeImageMap(writer, "map-name", info, true); //$NON-NLS-1$
    }
}

From source file:com.naryx.tagfusion.cfm.tag.awt.cfCHART.java

private String saveChartToFile(JFreeChart chart, byte _format, int width, int height, ChartRenderingInfo info)
        throws IOException {
    File tempFile;//from   w  ww. j  av a2s  .c  o  m
    if (_format == FORMAT_JPG) {
        tempFile = File.createTempFile("cfchart", ".jpeg", cfchartDirectory);
        ChartUtilities.saveChartAsJPEG(tempFile, chart, width, height, info);
    } else {
        tempFile = File.createTempFile("cfchart", ".png", cfchartDirectory);
        ChartUtilities.saveChartAsPNG(tempFile, chart, width, height, info);
    }
    String filename = tempFile.getName();

    // Check if charts are being cached
    if (storageCacheSize > 0) {
        synchronized (storageCache) {
            // If we've reached the cache limit then delete the oldest cached chart.
            if (storageCache.size() == storageCacheSize) {
                String oldestChart = storageCache.remove(0);
                File fileToDelete = new File(cfchartDirectory, oldestChart);
                fileToDelete.delete();
            }

            // Add the new chart to the end of the list of cached charts
            storageCache.add(filename);
        }
    }

    return filename;
}