Example usage for org.jfree.chart ChartUtilities writeChartAsPNG

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

Introduction

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

Prototype

public static void writeChartAsPNG(OutputStream out, JFreeChart chart, int width, int height)
        throws IOException 

Source Link

Document

Writes a chart to an output stream in PNG format.

Usage

From source file:com.sun.portal.os.portlets.ChartServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    OutputStream out = response.getOutputStream();

    try {/*from   ww  w  . j a v a2s .c  o  m*/
        JFreeChart chart = createChart(request);
        if (chart != null) {
            response.setContentType(CONTENT_TYPE_IMG_PNG);
            ChartUtilities.writeChartAsPNG(out, chart, 400, 300);
        }
    } catch (Exception e) {
        System.err.println(e.toString());
    } finally {
        out.close();
    }
}

From source file:org.projectforge.web.wicket.JFreeChartImage.java

@SuppressWarnings("serial")
@Override/*from  w ww  .  j a va2  s  . c  o m*/
protected AbstractResource getImageResource() {
    final String format = this.imageType == JFreeChartImageType.JPEG ? "jpg" : "png";
    return new DynamicImageResource() {

        @Override
        protected byte[] getImageData(final Attributes attributes) {
            try {
                final JFreeChart chart = (JFreeChart) getDefaultModelObject();
                final ByteArrayOutputStream baos = new ByteArrayOutputStream();
                if (imageType == JFreeChartImageType.JPEG) {
                    ChartUtilities.writeChartAsJPEG(baos, chart, width, height);
                } else {
                    ChartUtilities.writeChartAsPNG(baos, chart, width, height);
                }
                final byte[] ba = baos.toByteArray();
                return ba;
            } catch (final IOException ex) {
                log.error(ex.getMessage(), ex);
                return null;
            }
        }

        @Override
        protected void configureResponse(final ResourceResponse response, final Attributes attributes) {
            super.configureResponse(response, attributes);

            // if (isCacheable() == false) {
            response.setCacheDuration(Duration.NONE);
            response.setCacheScope(CacheScope.PRIVATE);
            // }
        }
    };
}

From source file:com.geminimobile.chart.GeminiChartUtil.java

public void createReport(OutputStream out, List<ChartSeries> chartData, String strTitle,
        String strDomainAxisLabel) {

    strDomainAxisLabel = "Time Interval: " + strDomainAxisLabel;
    String strYAxisLabel;/*from  w ww . j  av a2  s. co  m*/
    //String strCategoryType = " ";
    strYAxisLabel = "Count";
    //SimpleDateFormat sdf = new SimpleDateFormat("MMMM-dd hh:mm a");

    //build a dataset as needed by JFreeChart
    //      note: strCategoryType is for a chart with multiple categories.
    //      i.e. idisplay multiple bars for each time interval.
    //

    TimeSeriesCollection dataSet = new TimeSeriesCollection();

    // For each series of data, create a TimeSeries
    for (int i = 0; i < chartData.size(); i++) {
        ChartSeries chartSeries = chartData.get(i);

        TimeSeries timeSeries = new TimeSeries(chartSeries.getName(), Millisecond.class);
        List<ChartValueByTime> data = chartSeries.getData();

        //int cumulValue = 0;
        for (int j = 0; j < data.size(); j++) {
            ChartValueByTime chartVal = data.get(j);

            Millisecond ms = new Millisecond(new Date(chartVal.getTime()));

            // *NOT* Store the cumulative value . So maintain a running total.                
            //cumulValue += chartVal.getValue();
            //timeSeries.add(ms, cumulValue);
            timeSeries.add(ms, chartVal.getValue());
        }
        dataSet.addSeries(timeSeries);
    }

    JFreeChart lineChart = ChartFactory.createTimeSeriesChart(strTitle, // chart title
            strDomainAxisLabel, // domain axis label
            strYAxisLabel, // range axis label
            dataSet, // data
            true, // legend
            false, // tooltips
            false // urls
    );

    try {
        ChartUtilities.writeChartAsPNG(out, lineChart, 800, 400);
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:com.googlecode.jchav.chart.Chart.java

/**
 * Creates a PNG graphic for the given data.
 *
 * @param out the stream to write the PNG to.  The caller is responsible
 *  for closing the stream.//  w w w.  jav  a  2 s  .c  om
 * 
 * @throws IOException if there was a problem creating the chart.
 */
public void write(final OutputStream out) throws IOException {
    ChartUtilities.writeChartAsPNG(out, chart, width, height);
}

From source file:org.tolven.web.servlet.PortletChartServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    String cohortType = request.getParameter("cohortType");
    if (cohortType == null) {
        throw new RuntimeException("A request cohortType cannot be null");
    }//from  w  w  w.ja v  a 2s  .c  o  m
    String snapshotType = request.getParameter("snapshotType");
    if (snapshotType == null) {
        throw new RuntimeException("A request snapshotType cannot be null");
    }
    String chartType = request.getParameter("chartType");
    if (chartType == null) {
        throw new RuntimeException("A request chartType cannot be null");
    }
    AccountUser accountUser = (AccountUser) request.getAttribute("accountUser");
    Date now = (Date) request.getAttribute("tolvenNow");
    JFreeChart chart = snapshotBean.getChart(cohortType, snapshotType, chartType, accountUser, now);
    int chartWidth = Integer.parseInt(accountUser.getAccount().getProperty()
            .get("org.tolven.analysis.bean.percenttimeseries.portlet.width"));
    int chartHeight = Integer.parseInt(accountUser.getAccount().getProperty()
            .get("org.tolven.analysis.bean.percenttimeseries.portlet.height"));
    try {
        ChartUtilities.writeChartAsPNG(response.getOutputStream(), chart, chartWidth, chartHeight);
    } catch (IOException ex) {
        throw new RuntimeException("Could not write PNG chart", ex);
    }
}

From source file:org.shredzone.bullshitcharts.servlet.ChartServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    String pathInfo = req.getPathInfo();
    PlotGenerator generator = null;//from  w  ww  .  j a va  2 s.  co  m
    if ("/pie.png".equals(pathInfo)) {
        generator = new ChoicePieGenerator();
    } else if ("/agree.png".equals(pathInfo)) {
        generator = new AgreementPieGenerator();
    } else if ("/line.png".equals(pathInfo)) {
        generator = new LineChartGenerator();
    } else if ("/bar.png".equals(pathInfo)) {
        generator = new BarChartGenerator();
    } else {
        resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    generator.configure(req);

    Plot plot = generator.generate();

    // Generate the chart
    JFreeChart chart = new JFreeChart(plot);
    chart.setAntiAlias(true);
    chart.setTextAntiAlias(true);
    chart.setBorderVisible(false);
    chart.removeLegend();

    String title = req.getParameter("title");
    if (title != null) {
        chart.setTitle(title);
    }

    // Write the chart to a byte array. It is small enough so it won't load the
    // server's memory too much.
    try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
        ChartUtilities.writeChartAsPNG(baos, chart, IMAGE_WIDTH, IMAGE_HEIGHT);
        byte[] data = baos.toByteArray();

        // Stream the chart
        resp.setContentType("image/png");
        resp.setContentLength(data.length);
        resp.setHeader("Cache-Control", "no-cache, must-revalidate");
        resp.setHeader("Expires", "Sat, 01 Jan 2000 00:00:00 GMT");
        resp.getOutputStream().write(data);
    }
}

From source file:de.perdian.apps.dashboard.support.chart.ChartCreator.java

public String createChartAsImageContent(XYDataset dataset) {
    JFreeChart chart = this.createChart(dataset);
    try {//from   ww w.jav  a 2s.c om
        ByteArrayOutputStream burndownImageStream = new ByteArrayOutputStream();
        ChartUtilities.writeChartAsPNG(burndownImageStream, chart, this.getWidth(), this.getHeight());
        return "data:image/png;base64," + Base64.encodeBase64String(burndownImageStream.toByteArray());
    } catch (Exception e) {
        throw new DashboardException("Cannot create burndown chart", e);
    }
}

From source file:net.sf.jsfcomp.chartcreator.Chartlet.java

private void writeChart(HttpServletResponse response, JFreeChart chart, ChartData chartData)
        throws IOException {
    OutputStream stream = response.getOutputStream();
    response.setContentType(ChartUtils.resolveContentType(chartData.getOutput()));

    if (chartData.getOutput().equalsIgnoreCase("png"))
        ChartUtilities.writeChartAsPNG(stream, chart, chartData.getWidth(), chartData.getHeight());
    else if (chartData.getOutput().equalsIgnoreCase("jpeg"))
        ChartUtilities.writeChartAsJPEG(stream, chart, chartData.getWidth(), chartData.getHeight());

    stream.flush();//w w w  .  ja  va 2  s  . c  o m
    stream.close();
}

From source file:net.sourceforge.subsonic.controller.FolderChartController.java

public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    String type = request.getParameter("type");
    CategoryDataset dataset = createDataset(type);
    JFreeChart chart = createChart(dataset, request);

    int imageHeight = IMAGE_MIN_HEIGHT * dataset.getColumnCount();
    if (imageHeight < 100) {
        imageHeight = 100;/* ww w  .j  a  v  a 2 s.c om*/
    }

    ChartUtilities.writeChartAsPNG(response.getOutputStream(), chart, IMAGE_WIDTH, imageHeight);
    return null;
}

From source file:br.senac.tads.pi3.ghosts.locarsys.dao.Relatorios.java

public static void relatoriosVendas() throws SQLException, ClassNotFoundException {
    String query = "SELECT FL.NOME_FILIAL, COUNT(FL.NOME_FILIAL) AS QUANTIDADE FROM FILIAL FL "
            + "INNER JOIN FUNCIONARIO FUNC ON FUNC.ID_FILIAL = FL.ID_FILIAL "
            + "INNER JOIN ALUGUEL AL ON AL.ID_FUNCIONARIO = FUNC.ID_FUNCIONARIO " + "GROUP BY FL.NOME_FILIAL";
    Connection conn = Conexoes.obterConexao();
    Statement stmt = conn.createStatement();

    ResultSet rs = stmt.executeQuery(query);

    DefaultCategoryDataset ds = new DefaultCategoryDataset();

    while (rs.next()) {
        ds.addValue(rs.getInt("QUANTIDADE"), "Quantidade", rs.getString("NOME_FILIAL"));
    }/* w  w  w.  j  ava 2s  .com*/

    JFreeChart grafico = ChartFactory.createBarChart3D("Relatrio de Aluguis", "Filiais",
            "Separadas por filiais", ds, PlotOrientation.VERTICAL, true, true, false);

    try (OutputStream arquivo = new FileOutputStream("ImagensLoCarSys\\vendas.png")) {
        ChartUtilities.writeChartAsPNG(arquivo, grafico, 800, 600);
    } catch (FileNotFoundException ex) {
        System.out.println("" + ex.getMessage());
    } catch (IOException ex) {
        System.out.println("" + ex.getMessage());
    }

    //try (OutputStream arquivo = new FileOutputStream("C:\\Users\\bruno.clopes\\Documents\\NetBeansProjects\\LoCarSys\\target\\LoCarSys-1.0-SNAPSHOT\\ImagensLoCarSys\\vendas.png")) {
    try (OutputStream arquivo = new FileOutputStream(
            "C:\\Users\\temp.cas\\Documents\\NetBeansProjects\\LoCarSys\\target\\LoCarSys-1.0-SNAPSHOT\\ImagensLoCarSys\\vendas.png")) {
        ChartUtilities.writeChartAsPNG(arquivo, grafico, 800, 600);
    } catch (FileNotFoundException ex) {
        System.out.println("" + ex.getMessage());
    } catch (IOException ex) {
        System.out.println("" + ex.getMessage());
    }
}