Example usage for org.jfree.chart JFreeChart createBufferedImage

List of usage examples for org.jfree.chart JFreeChart createBufferedImage

Introduction

In this page you can find the example usage for org.jfree.chart JFreeChart createBufferedImage.

Prototype

public BufferedImage createBufferedImage(int width, int height) 

Source Link

Document

Creates and returns a buffered image into which the chart has been drawn.

Usage

From source file:com.estate.pdf.Page.java

protected void drawTaxPie(Rectangle rct, double totalValue, double tax, String taxLabel, String netLabel) {
    double taxPercent = (tax / totalValue) * 100;
    double netValuePercent = 100 - taxPercent;

    DefaultPieDataset dataset = new DefaultPieDataset();
    dataset.setValue(taxLabel, taxPercent);
    dataset.setValue(netLabel, netValuePercent);

    PiePlot3D plot = new PiePlot3D(dataset);
    plot.setLabelGenerator(new StandardPieItemLabelGenerator());
    plot.setInsets(new Insets(0, 5, 5, 5));
    plot.setToolTipGenerator(new CustomeGenerators.CustomToolTipGenerator());
    plot.setLabelGenerator(new CustomeGenerators.CustomLabelGenerator());
    plot.setSectionPaint(0, new Color(pgRed));
    plot.setSectionPaint(1, new Color(pgGreen));
    plot.setForegroundAlpha(.6f);/*from  w  w w  .  j ava  2 s. c  om*/
    plot.setOutlinePaint(Color.white);
    plot.setBackgroundPaint(Color.white);

    JFreeChart chart = new JFreeChart("", JFreeChart.DEFAULT_TITLE_FONT, plot, true);

    chart.setBackgroundPaint(Color.white);
    chart.setAntiAlias(true);

    Rectangle page = rct;

    try {
        Image img = Image.getInstance(chart.createBufferedImage((int) page.getWidth(), (int) page.getHeight()),
                null);
        drawDiagram(img, rct, 0, 72);
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }

}

From source file:velo.ejb.seam.action.HomeActionsBean.java

public void createChart() {
    ResourceList rl = new ResourceList();
    rl.getResource().setActive(true);//www  . j ava 2  s . c o  m
    rl.initialize();
    List<Resource> resources = rl.getResultList();

    //Retrieve a list of tasks from last day
    TaskList tl = new TaskList();
    List<Task> tasks = tl.getResultList();

    //build the summaries
    Map<String, Long> rTasks = new HashMap<String, Long>();

    for (Task currTask : tasks) {
        if (currTask instanceof ResourceTask) {
            ResourceTask rt = (ResourceTask) currTask;

            if (!rTasks.containsKey(rt.getResourceUniqueName())) {
                rTasks.put(rt.getResourceUniqueName(), new Long(0));
            }

            rTasks.put(rt.getResourceUniqueName(), rTasks.get(rt.getResourceUniqueName()) + 1);
        }
    }

    final DefaultPieDataset dataset = new DefaultPieDataset();
    for (Resource currResource : resources) {
        if (rTasks.containsKey(currResource.getUniqueName())) {
            dataset.setValue(currResource.getDisplayName() + "("
                    + rTasks.get(currResource.getUniqueName()).longValue() + ")",
                    rTasks.get(currResource.getUniqueName()));
        } else {
            dataset.setValue(currResource.getDisplayName() + "(0)", 0);
        }

    }

    final JFreeChart chart = ChartFactory.createPieChart("Tasks Amount (1 last day) per resource", // chart title
            dataset, // dataset
            true, // include legend
            true, false);
    final PiePlot plot = (PiePlot) chart.getPlot();
    plot.setNoDataMessage("No data available");

    try {
        this.chart = ChartUtilities.encodeAsPNG(chart.createBufferedImage(400, 400));
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:com.wicht.benchmark.utils.Benchs.java

/**
 * Generate the chart.//www  .j  av  a2  s  .  co m
 *
 * @param title      The title of the chart.
 * @param benchmarks The benchmarks to include in the chart.
 * @param sub        A boolean tag indicating if we want to generate sub chart ({@code true}) or not ({@code
 *                   false}).
 * @param prefix     The time prefix.
 */
private void generateChart(String title, Collection<NamedBenchmark> benchmarks, boolean sub, Prefix prefix) {
    String data = "Time (" + prefix.getSymbol() + "s)";

    DefaultCategoryDataset dataset = new DefaultCategoryDataset();

    for (NamedBenchmark benchmark : benchmarks) {
        dataset.addValue(getExactMean(benchmark.getMean(), prefix), "", benchmark.getTitle());
    }

    JFreeChart chart = ChartFactory.createBarChart(title.replace("-sub", ""), "Methods", data, dataset,
            PlotOrientation.VERTICAL, false, false, false);

    final CategoryAxis domainAxis = chart.getCategoryPlot().getDomainAxis();
    domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);
    domainAxis.setMaximumCategoryLabelLines(5);

    BufferedImage image = chart.createBufferedImage(width, height);

    try {
        ImageIO.write(image, "png", new File(folder + title + ".png"));
    } catch (IOException e) {
        e.printStackTrace();
    }

    if (sub) {
        generateSubChart(title, benchmarks);
    }
}

From source file:org.matsim.counts.algorithms.CountSimComparisonKMLWriter.java

/**
 * Writes the given JFreeChart to the kmz file specified for the kmz writer attribute of this class.
 * @param filename the filename to use in the kmz
 * @param chart/*from   ww  w  .j a  va2 s .c om*/
 * @throws IOException
 */
private void writeChartToKmz(final String filename, final JFreeChart chart) throws IOException {
    byte[] img;
    img = ChartUtilities.encodeAsPNG(chart.createBufferedImage(CHARTWIDTH, CHARTHEIGHT));
    this.writer.addNonKMLFile(img, filename);
}

From source file:Visao.Relatorio.Relatorio_QuantidadeReclamacoesSexo.java

public void create(OutputStream outputStream, JFreeChart chart) throws DocumentException, IOException {
    Document document = null;/*from   w w w. j ava 2 s.co  m*/
    PdfWriter writer = null;

    try {
        //instantiate document and writer
        document = new Document();
        writer = PdfWriter.getInstance(document, outputStream);

        //open document
        document.open();
        Image img = Image.getInstance("src\\Imagens\\logo.png");
        img.setAlignment(Element.ALIGN_CENTER);
        document.add(img);

        //add image
        int width = 400;
        int height = 300;

        BufferedImage bufferedImage = chart.createBufferedImage(width, height);
        Image image = Image.getInstance(writer, bufferedImage, 1.0f);
        document.add(image);

        String saida = "\n\n" + controleRelatorio.numeroReclamacoesSexo();
        document.add(new Paragraph(saida));

        //release resources
        document.close();
        document = null;

        writer.close();
        writer = null;
    } catch (DocumentException | IOException de) {
        throw de;
    } finally {
        //release resources
        if (null != document) {
            try {
                document.close();
            } catch (Exception ex) {
            }
        }

        if (null != writer) {
            try {
                writer.close();
            } catch (Exception ex) {
            }
        }
    }
}

From source file:se.sics.kompics.p2p.monitor.cyclon.server.CyclonMonitorServer.java

private void printAlivePeers(StringBuilder sb, boolean showPeers) {

    long t0 = System.currentTimeMillis();
    GraphUtil g = new GraphUtil(alivePeers);
    long t1 = System.currentTimeMillis();

    double id, od, cc, pl, istd;
    int diameter;

    id = g.getMeanInDegree();//from  ww  w. ja v a  2  s  .c  om
    istd = g.getInDegreeStdDev();
    od = g.getMeanOutDegree();
    cc = g.getMeanClusteringCoefficient();
    pl = g.getMeanPathLength();
    diameter = g.getDiameter();
    int netSize = g.getNetworkSize();

    sb.append("<h2 align=\"center\" class=\"style2\">");
    sb.append("View of Cyclon Random Overlay:</h2>");
    sb.append("<table width=\"400\" border=\"1\" align=\"center\"><tr>");
    sb.append("<th class=\"style2\" width=\"250\" scope=\"col\">Metric");
    sb.append("</th><th class=\"style2\"");
    sb.append(" width=\"150\" scope=\"col\">Value</th></tr><tr>");

    sb.append("<td>Network size</td><td><div align=\"center\">");
    sb.append(netSize).append("</div></td></tr>");
    sb.append("<td>Disconnected node pairs</td><td><div align=\"center\">");
    sb.append(g.getInfinitePathCount()).append("/");
    sb.append(netSize * (netSize - 1)).append("</div></td></tr>");
    sb.append("<td>Diameter</td><td><div align=\"center\">");
    sb.append(diameter).append("</div></td></tr>");
    sb.append("<td>Average path length</td><td><div align=\"center\">");
    sb.append(String.format("%.4f", pl)).append("</div></td></tr>");
    sb.append("<td>Clustering-coefficient</td><td><div align=\"center\">");
    sb.append(String.format("%.4f", cc)).append("</div></td></tr>");
    sb.append("<td>Average in-degree</td><td><div align=\"center\">");
    sb.append(String.format("%.4f", id)).append("</div></td></tr>");
    sb.append("<td>In-degree standard deviation</td><td><div align=\"center\">");
    sb.append(String.format("%.4f", istd)).append("</div></td></tr>");
    sb.append("<td>Average out-degree</td><td><div align=\"center\">");
    sb.append(String.format("%.4f", od)).append("</div></td></tr>");
    sb.append("</table>");

    // print in-degree distribution
    HistogramDataset dataset = new HistogramDataset();
    double[] values = g.getInDegrees();
    int min = (int) g.getMinInDegree(), max = (int) g.getMaxInDegree();
    int bins = max - min;
    bins = bins < 1 ? 1 : bins;
    dataset.addSeries("In-degree distribution", values, bins, min, max);
    JFreeChart chart = ChartFactory.createHistogram(null, null, null, dataset, PlotOrientation.VERTICAL, true,
            false, false);
    // chart.getXYPlot().setForegroundAlpha(0.95f);
    BufferedImage image = chart.createBufferedImage(800, 300);

    String imageString = "";
    try {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ImageIO.write(image, "png", out);
        out.close();
        Base64 bencoder = new Base64();
        imageString = new String(bencoder.encode(out.toByteArray()));
        imageString = "data:image/png;base64," + imageString;
    } catch (IOException e) {
        sb.append(e);
    }

    sb.append("<br><div align=\"center\"><img src=\"").append(imageString);
    sb.append("\" alt=\"In-degree distribution " + "\" /></div><br>");

    sb.append("<div align=\"center\">It took ").append(t1 - t0);
    sb.append("ms to compute these statistics.<br>");

    // refresh form
    sb.append("<form method=\"get\" name=\"rfrshFrm\" id=\"rfrshFrm\">");
    sb.append("<label>Show peers ");
    sb.append("<input name=\"peers\" type=\"checkbox\" id=\"peers\" />");
    // sb.append("checked=\"").append("false").append("\" />");
    sb.append("<input type=\"submit\" value=\"Refresh\" />");
    sb.append("</form></div>");

    if (!showPeers) {
        return;
    }

    sb.append("<h2 align=\"center\" class=\"style2\">");
    sb.append("Individual peers:</h2>");
    sb.append("<table width=\"1300\" border=\"1\" align=\"center\"><tr>");
    sb.append("<th class=\"style2\" width=\"50\" scope=\"col\">Count</th>");
    sb.append("<th class=\"style2\" width=\"50\" scope=\"col\">Peer</th>");
    sb.append("<th class=\"style2\" width=\"800\" scope=\"col\">Neighbors</th>");
    sb.append("<th class=\"style2\" width=\"50\" scope=\"col\">In Degree</th>");
    sb.append("<th class=\"style2\" width=\"50\" scope=\"col\">Out Degree</th>");
    sb.append("<th class=\"style2\" width=\"100\" scope=\"col\">Cluestering Coefficient</th>");
    sb.append("<th class=\"style2\" width=\"50\" scope=\"col\">Age</th>");
    sb.append("<th class=\"style2\" width=\"100\" scope=\"col\">Freshness</th></tr>");

    int count = 1;

    for (OverlayAddress address : alivePeers.keySet()) {
        CyclonNeighbors neighbors = alivePeers.get(address);

        List<CyclonNodeDescriptor> descriptors = neighbors.getDescriptors();
        Collections.sort(descriptors);

        sb.append("<tr>");
        sb.append("<td><div align=\"center\">").append(count++);
        // sb.append("(").append(g.map.get(address)).append(")");
        sb.append("</div></td>");

        // print peer address
        sb.append("</div></td><td bgcolor=\"#99CCFF\"><div align=\"center\">");
        appendPeerLink(sb, address);
        sb.append("</div></td>");

        // print neighbors
        if (descriptors != null) {
            sb.append("<td><div align=\"left\">");
            sb.append("[");
            Iterator<CyclonNodeDescriptor> iter = descriptors.iterator();
            while (iter.hasNext()) {
                appendPeerLink(sb, iter.next().getCyclonAddress());
                if (iter.hasNext()) {
                    sb.append(", ");
                }
            }
            sb.append("]");
        } else {
            sb.append("<td bgcolor=\"#FFCCFF\"><div align=\"left\">");
            sb.append("[empty]");
        }
        sb.append("</div></td>");

        int v = g.getNodeIndexByAddress(address);

        // print in-degree
        sb.append("<td><div align=\"center\">").append(g.getInDegree(v));
        sb.append("</div></td>");
        // print out-degree
        sb.append("<td><div align=\"center\">").append(g.getOutDegree(v));
        sb.append("</div></td>");
        // print clustering coefficient

        // directedGraph

        sb.append("<td><div align=\"center\">").append(String.format("%.4f", g.getClustering(v)));
        sb.append("</div></td>");

        long now = System.currentTimeMillis();
        OverlayViewEntry viewEntry = view.get(address);

        // print age
        sb.append("<td><div align=\"right\">");
        sb.append(durationToString(now - viewEntry.getAddedAt()));
        sb.append("</div></td>");

        // print freshness
        sb.append("<td><div align=\"right\">");
        sb.append(durationToString(now - viewEntry.getRefreshedAt()));
        sb.append("</div></td>");

        sb.append("</tr>");
    }
    sb.append("</table>");
}

From source file:weka.gui.beans.JFreeChartOffscreenChartRenderer.java

/**
 * Render an XY line chart//w  w  w . j  a va 2 s.c om
 * 
 * @param width the width of the resulting chart in pixels
 * @param height the height of the resulting chart in pixels
 * @param series a list of Instances - one for each series to be plotted
 * @param xAxis the name of the attribute for the x-axis (all series Instances
 *          are expected to have an attribute of the same type with this name)
 * @param yAxis the name of the attribute for the y-axis (all series Instances
 *          are expected to have an attribute of the same type with this name)
 * @param optionalArgs optional arguments to the renderer (may be null)
 * 
 * @return a BufferedImage containing the chart
 * @throws Exception if there is a problem rendering the chart
 */
public BufferedImage renderXYLineChart(int width, int height, List<Instances> series, String xAxis,
        String yAxis, List<String> optionalArgs) throws Exception {

    String plotTitle = "Line Chart";
    String userTitle = getOption(optionalArgs, "-title");
    plotTitle = (userTitle != null) ? userTitle : plotTitle;
    String colorAtt = getOption(optionalArgs, "-color");

    if (series.size() == 1 & colorAtt != null && colorAtt.length() > 0) {
        int colIndex = getIndexOfAttribute(series.get(0), colorAtt);
        if (colIndex >= 0 && series.get(0).attribute(colIndex).isNominal()) {
            // split single series out into multiple instances objects - one
            // per class
            series = splitToClasses(series.get(0), colIndex);
            for (Instances insts : series) {
                insts.setClassIndex(colIndex);
            }
        }
    }

    Instances masterInstances = series.get(0);
    int xAx = getIndexOfAttribute(masterInstances, xAxis);
    int yAx = getIndexOfAttribute(masterInstances, yAxis);
    if (xAx < 0) {
        xAx = 0;
    }
    if (yAx < 0) {
        yAx = 0;
    }

    // Set the axis names just in case we've been supplied with
    // /first, /last or /<num>
    xAxis = masterInstances.attribute(xAx).name();
    yAxis = masterInstances.attribute(yAx).name();

    XYSeriesCollection xyDataset = new XYSeriesCollection();
    // add master series
    XYSeries master = new XYSeries(masterInstances.relationName(), false);
    for (int i = 0; i < masterInstances.numInstances(); i++) {
        Instance inst = masterInstances.instance(i);
        if (!inst.isMissing(xAx) && !inst.isMissing(yAx)) {
            master.add(inst.value(xAx), inst.value(yAx));
        }
    }
    xyDataset.addSeries(master);

    // remaining series
    for (int i = 1; i < series.size(); i++) {
        Instances aSeriesI = series.get(i);
        XYSeries aSeriesJ = new XYSeries(aSeriesI.relationName(), false);
        for (int j = 0; j < aSeriesI.numInstances(); j++) {
            Instance inst = aSeriesI.instance(j);
            if (!inst.isMissing(xAx) && !inst.isMissing(yAx)) {
                aSeriesJ.add(inst.value(xAx), inst.value(yAx));
            }
        }
        xyDataset.addSeries(aSeriesJ);
    }

    JFreeChart chart = ChartFactory.createXYLineChart(userTitle, xAxis, yAxis, xyDataset,
            PlotOrientation.VERTICAL, true, false, false);
    chart.setBackgroundPaint(java.awt.Color.white);

    BufferedImage image = chart.createBufferedImage(width, height);

    return image;
}

From source file:Visao.Relatorio.Relatorio_QuantidadeReclamacoesUF.java

public void create(OutputStream outputStream, JFreeChart chart) throws DocumentException, IOException {
    Document document = null;//from   w  w w  . j a  va2 s  . c o  m
    PdfWriter writer = null;

    try {
        //instantiate document and writer
        document = new Document();
        writer = PdfWriter.getInstance(document, outputStream);

        //open document
        document.open();
        Image img = Image.getInstance("src\\Imagens\\logo.png");
        img.setAlignment(Element.ALIGN_CENTER);
        document.add(img);

        //add image
        int width = 500;
        int height = 400;

        BufferedImage bufferedImage = chart.createBufferedImage(width, height);
        Image image = Image.getInstance(writer, bufferedImage, 1.0f);
        document.add(image);

        Font boldFont = new Font(Font.FontFamily.TIMES_ROMAN, 18, Font.BOLD);
        String quebralinha = "\n\nQuantidade de reclamaes por UF\n\n";
        Paragraph preface = new Paragraph(quebralinha, boldFont);
        preface.setAlignment(Element.ALIGN_CENTER);
        document.add(preface);

        PdfPTable table = new PdfPTable(2);

        PdfPCell pdfWordCell = new PdfPCell();
        PdfPCell pdfWordCell1 = new PdfPCell();
        Phrase firstLine = new Phrase("UF", new Font(Font.FontFamily.TIMES_ROMAN, 14, Font.BOLD));
        Phrase secondLine = new Phrase("Quantidade", new Font(Font.FontFamily.TIMES_ROMAN, 14, Font.BOLD));

        pdfWordCell.addElement(firstLine);
        pdfWordCell1.addElement(secondLine);

        table.addCell(pdfWordCell);
        table.addCell(pdfWordCell1);

        String consulta = "Select uf, count(codigoreclamacao) from "
                + "Reclamacao group by (uf) order by count(codigoreclamacao) desc";

        Iterator i = dao.getSessao().createSQLQuery(consulta).list().iterator();

        while (i.hasNext()) {
            Object[] reclamacao = (Object[]) i.next();
            table.addCell(reclamacao[0].toString());
            table.addCell(reclamacao[1].toString());
        }

        document.add(table);

        //release resources
        document.close();
        document = null;

        writer.close();
        writer = null;
    } catch (DocumentException | IOException de) {
        throw de;
    } finally {
        //release resources
        if (null != document) {
            try {
                document.close();
            } catch (Exception ex) {
            }
        }

        if (null != writer) {
            try {
                writer.close();
            } catch (Exception ex) {
            }
        }
    }
}

From source file:org.drools.planner.benchmark.SolverBenchmarkSuite.java

private CharSequence writeBestScoreSummaryChart() {
    DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    for (SolverBenchmark solverBenchmark : solverBenchmarkList) {
        ScoreDefinition scoreDefinition = solverBenchmark.getLocalSearchSolverConfig()
                .getScoreDefinitionConfig().buildScoreDefinition();
        for (SolverBenchmarkResult result : solverBenchmark.getSolverBenchmarkResultList()) {
            Score score = result.getScore();
            Double scoreGraphValue = scoreDefinition.translateScoreToGraphValue(score);
            String solverLabel = solverBenchmark.getName();
            if (solverBenchmark.getRanking() == 0) {
                solverLabel += " (winner)";
            }/*from  ww w.j a v  a 2s.c om*/
            dataset.addValue(scoreGraphValue, solverLabel, result.getUnsolvedSolutionFile().getName());
        }
    }
    JFreeChart chart = ChartFactory.createBarChart("Best score summary (higher score is better)", "Data",
            "Score", dataset, PlotOrientation.VERTICAL, true, true, false);
    CategoryItemRenderer renderer = ((CategoryPlot) chart.getPlot()).getRenderer();
    CategoryItemLabelGenerator generator = new StandardCategoryItemLabelGenerator();
    renderer.setBaseItemLabelGenerator(generator);
    renderer.setBaseItemLabelsVisible(true);
    BufferedImage chartImage = chart.createBufferedImage(1024, 768);
    File chartSummaryFile = new File(solverStatisticFilesDirectory, "summary.png");
    OutputStream out = null;
    try {
        out = new FileOutputStream(chartSummaryFile);
        ImageIO.write(chartImage, "png", out);
    } catch (IOException e) {
        throw new IllegalArgumentException("Problem writing graphStatisticFile: " + chartSummaryFile, e);
    } finally {
        IOUtils.closeQuietly(out);
    }
    return "  <img src=\"" + chartSummaryFile.getName() + "\"/>\n";
}

From source file:org.tiefaces.components.websheet.chart.ChartHelper.java

/**
 * Generate single XSSF chart./*from   w w w  .j  a  va 2  s  .  com*/
 * 
 * @param chart
 *            the chart
 * @param chartId
 *            the chart id
 * @param sheet
 *            the sheet
 * @param anchorMap
 *            the anchor map
 * @param chartMap
 *            the chart map
 * @param chartDataMap
 *            the chart data map
 */
private void generateSingleXSSFChart(final XSSFChart chart, final String chartId, final XSSFSheet sheet,
        final Map<String, ClientAnchor> anchorMap, final Map<String, BufferedImage> chartMap,
        final Map<String, ChartData> chartDataMap) {
    ClientAnchor anchor;
    try {
        anchor = anchorMap.get(chartId);
        if (anchor != null) {
            ChartData chartData = ChartUtility.initChartDataFromXSSFChart(chartId, chart,
                    (XSSFWorkbook) parent.getWb());
            chartDataMap.put(chartId, chartData);
            JFreeChart jchart = createChart(chartData);
            if (jchart != null) {
                AnchorSize anchorSize = PicturesUtility.getAnchorSize(sheet, null, null, anchor);
                BufferedImage img = jchart.createBufferedImage(anchorSize.getWidth(), anchorSize.getHeight());
                chartMap.put(chartId, img);
            }
        }
    } catch (Exception ex) {
        LOG.log(Level.SEVERE, "generate chart for " + chartId + " error = " + ex.getLocalizedMessage(), ex);
    }
}