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, ChartRenderingInfo info) 

Source Link

Document

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

Usage

From source file:nextapp.echo.chart.webcontainer.service.ChartImageService.java

public void service(Connection conn) throws IOException {
    try {/*from  www .j a  v  a 2 s.  com*/
        UserInstance userInstance = (UserInstance) conn.getUserInstance();
        if (userInstance == null) {
            serviceBadRequest(conn, "No container available.");
            return;
        }

        HttpServletRequest request = conn.getRequest();
        String chartId = request.getParameter("chartId");
        ChartDisplay chartDisplay = (ChartDisplay) userInstance.getApplicationInstance()
                .getComponentByRenderId(chartId);
        synchronized (chartDisplay) {
            if (chartDisplay == null || !chartDisplay.isRenderVisible()) {
                throw new IllegalArgumentException("Invalid chart id.");
            }

            Extent ewidth = (Extent) chartDisplay.getRenderProperty(ChartDisplay.PROPERTY_WIDTH);
            int width = ewidth != null ? ewidth.getValue() : ChartDisplayPeer.DEFAULT_WIDTH;

            Extent eheight = (Extent) chartDisplay.getRenderProperty(ChartDisplay.PROPERTY_HEIGHT);
            int height = ewidth != null ? eheight.getValue() : ChartDisplayPeer.DEFAULT_HEIGHT;

            JFreeChart chart = chartDisplay.getChart();
            BufferedImage image;
            ChartRenderingInfo info = new ChartRenderingInfo();
            synchronized (chart) {
                image = chart.createBufferedImage(width, height, info);
            }
            //                EntityCollection coll = info.getEntityCollection();
            //                debug("About to show entities");
            //                for (int i = 0; i < coll.getEntityCount(); i++) {
            //                   debug("Entity: " + coll.getEntity(i).getShapeCoords());
            //                   debug("Entity: " + coll.getEntity(i).getShapeType());
            //                   debug("Entity: " + coll.getEntity(i).getToolTipText());
            //                }

            PngEncoder encoder = new PngEncoder(image, true, null, 3);
            conn.setContentType(ContentType.IMAGE_PNG);
            OutputStream out = conn.getOutputStream();
            encoder.encode(out);
        }
    } catch (IOException ex) {
        // Internet Explorer appears to enjoy making half-hearted requests for images, wherein it resets the connection
        // leaving us with an IOException.  This exception is silently eaten.
        ex.printStackTrace();
    }
}

From source file:probe.com.view.body.quantcompare.PieChart.java

private String saveToFile(final JFreeChart chart, final double width, final double height) {
    byte imageData[];
    try {//from   w  ww.  j  a va2 s . c  om

        imageData = ChartUtilities
                .encodeAsPNG(chart.createBufferedImage((int) width, (int) height, chartRenderingInfo));
        String base64 = Base64.encodeBase64String(imageData);
        base64 = "data:image/png;base64," + base64;
        return base64;
    } catch (IOException e) {
        System.err.println("at error " + e.getMessage());
    }
    return "";
}

From source file:org.n52.server.io.Generator.java

protected String createAndSaveImage(DesignOptions options, JFreeChart chart, ChartRenderingInfo renderingInfo)
        throws GeneratorException {
    int width = options.getWidth();
    int height = options.getHeight();
    BufferedImage image = chart.createBufferedImage(width, height, renderingInfo);
    Graphics2D chartGraphics = image.createGraphics();
    chartGraphics.setColor(Color.white);
    chartGraphics.fillRect(0, 0, width, height);
    chart.draw(chartGraphics, new Rectangle2D.Float(0, 0, width, height));

    try {/*from  w ww.j  a v  a 2 s.c o m*/
        return ServletUtilities.saveChartAsPNG(chart, width, height, renderingInfo, null);
    } catch (IOException e) {
        throw new GeneratorException("Could not save PNG!", e);
    }
}

From source file:org.openfaces.component.chart.ChartView.java

public byte[] renderAsImageFile() {
    Chart chart = getChart();//from  w w  w .j  a va2  s.  c o m
    JfcRenderHints renderHints = chart.getRenderHints();
    ChartRenderingInfo chartRenderingInfo = new ChartRenderingInfo();
    renderHints.setRenderingInfo(chartRenderingInfo);

    ChartModel model = chart.getModel();
    ModelInfo info = new ModelInfo(model);
    renderHints.setModelInfo(info);

    Plot plot = createPlot(chart, model, info);
    JFreeChart jFreeChart = new JFreeChartAdapter(plot, chart);
    int width = chart.getWidth();
    int height = chart.getHeight();
    BufferedImage image = jFreeChart.createBufferedImage(width, height, chartRenderingInfo);
    byte[] imageAsByteArray = Rendering.encodeAsPNG(image);

    String mapId = renderHints.getMapId(chart);
    if (mapId != null) {
        String map = MapRenderUtilities.getImageMapExt(chart, mapId, chartRenderingInfo,
                new StandardToolTipTagFragmentGenerator(), new StandardURLTagFragmentGenerator());
        renderHints.setMap(map);
    }

    return imageAsByteArray;
}

From source file:org.openfaces.component.chart.Chart.java

public BufferedImage make() {
    JFreeChart jFreeChart = getJFreeChart();
    ChartRenderingInfo chartRenderingInfo = renderHints.getRenderingInfo();

    return jFreeChart.createBufferedImage(getWidth(), getHeight(), chartRenderingInfo);
}

From source file:org.jax.maanova.plot.RenderChartImageTask.java

/**
 * {@inheritDoc}//ww w. ja v  a 2 s  .  co m
 */
public void run() {
    try {
        while (true) {
            // wait until the chart needs to be updated
            this.renderRequestQueue.take();

            if (this.getWorkUnitsCompleted() == 1) {
                // each render cycle is a new work unit
                this.setTotalWorkUnits(1);
                this.setWorkUnitsCompleted(0);
            }

            // get a snapshot of the updated chart width and height
            JFreeChart tmpChart = this.chart;
            int tmpWidth = this.width;
            int tmpHeight = this.height;

            // if any values are bad leave the buffered image as null
            BufferedImage bi = null;
            if (tmpChart != null && tmpWidth > 0 && tmpHeight > 0) {
                bi = tmpChart.createBufferedImage(tmpWidth, tmpHeight, this.chartRenderingInfo);
            }

            if (bi != null) {
                // clear any old image before putting our shiny new image
                this.bufferedImageQueue.poll();
                this.bufferedImageQueue.put(bi);
            }

            // don't bother setting work to complete if we know there
            // is a pending request in the queue
            if (this.renderRequestQueue.isEmpty()) {
                this.setWorkUnitsCompleted(1);
            }
        }
    } catch (InterruptedException ex) {
        LOG.log(Level.SEVERE, "Error rendering chart image", ex);
    }
}

From source file:tdunnick.jphineas.console.queue.Charts.java

private BufferedImage getJFreeImage(JFreeChart image, int width, int height, ChartRenderingInfo info) {
    image.getTitle().setFont(new Font("Times New Roman", Font.BOLD, 16));
    image.setBackgroundPaint(new Color(255, 255, 255, 0));
    image.setBackgroundImageAlpha(0.0f);
    return (image.createBufferedImage(width, height, info));
}

From source file:domainhealth.frontend.graphics.JFreeChartGraphImpl.java

/**
 * Write a PNG image representation of the Graph to the given output 
 * stream//from   w  w w  .  j  a va2  s. c  om
 * 
 * @param out The output stream to write the PNG bytes to
 * @throws IOException Indicates a problem writing to the output stream
 */
public void writeGraphImage(int numServersDisplayed, OutputStream out) throws IOException {
    ValueAxis xAxis = new DateAxis(MonitorProperties.units(DATE_TIME));
    NumberAxis yAxis = new NumberAxis(yAxisUnits);
    yAxis.setAutoRangeIncludesZero(true);
    yAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    XYPlot xyPlotLine = new XYPlot(xySeriesCollection, xAxis, yAxis,
            new StandardXYItemRenderer(StandardXYItemRenderer.LINES));
    JFreeChart chart = new JFreeChart(chartTitle, JFreeChart.DEFAULT_TITLE_FONT, xyPlotLine, true);
    chart.setBackgroundPaint(java.awt.Color.white);
    // Increase size of graph height to accommodate large legends for when many servers in the domain
    int graphAdditionalHeight = GRAPH_INCREMENT_HEIGHT
            * ((int) (numServersDisplayed / GRAPH_INCREMENT_SERVER_RATIO));
    BufferedImage graphImage = chart.createBufferedImage(GRAPH_WIDTH,
            INITIAL_GRAPH_HEIGHT + graphAdditionalHeight,
            new ChartRenderingInfo(new StandardEntityCollection()));
    addNoDataLogoIfEmpty(graphImage);
    ChartUtilities.writeBufferedImageAsPNG(out, graphImage); // Could try extra two PNG related params: encodeAlpha and compression
}

From source file:fr.paris.lutece.plugins.stock.modules.billetterie.web.StatisticJspBean.java

/**
 * write in the http response the statistic graph of all response submit who
 * verify the date filter.//  w ww  .  ja v a2  s .c o  m
 *
 * @param request the http request
 * @param response The http response
 */
public void doGenerateGraph(HttpServletRequest request, HttpServletResponse response) {
    Locale locale = getLocale();
    String strFistResponseDateFilter = request.getParameter(PARAMETER_FIRST_RESPONSE_DATE_FILTER);
    String strLastResponseDateFilter = request.getParameter(PARAMETER_LAST_RESPONSE_DATE_FILTER);
    String strTimesUnit = request.getParameter(PARAMETER_TIMES_UNIT);
    String strTypeData = request.getParameter(PARAMETER_TYPE_DATA);

    List<ResultStatistic> listeResultStatistic = null;

    if (strTypeData.equals(CONSTANT_PRODUCT_TYPE)) {
        listeResultStatistic = _serviceStatistic.getProductStatistic(strTimesUnit, strFistResponseDateFilter,
                strLastResponseDateFilter);
    } else {
        listeResultStatistic = _serviceStatistic.getPurchaseStatistic(strTimesUnit, strFistResponseDateFilter,
                strLastResponseDateFilter);
    }

    String strNumberOfResponseAxisX = AppPropertiesService.getProperty(PROPERTY_NUMBER_RESPONSE_AXIS_X);
    int nNumberOfResponseAxisX = 10;

    try {
        nNumberOfResponseAxisX = Integer.parseInt(strNumberOfResponseAxisX);
    } catch (NumberFormatException ne) {
        AppLogService.error(ne);
    }

    List<ResultStatistic> listStatisticGraph = new ArrayList<ResultStatistic>();
    ResultStatistic statisticFormSubmit;

    if (listeResultStatistic.size() != 0) {
        for (int cpt = 0; cpt < nNumberOfResponseAxisX; cpt++) {
            statisticFormSubmit = new ResultStatistic();
            statisticFormSubmit.setNumberResponse(0);
            statisticFormSubmit.setStatisticDate(StatisticService
                    .addStatisticInterval(listeResultStatistic.get(0).getStatisticDate(), strTimesUnit, cpt));
            listStatisticGraph.add(statisticFormSubmit);
        }
    }

    for (ResultStatistic statisticFormSubmitGraph : listStatisticGraph) {
        for (ResultStatistic resultStatistic : listeResultStatistic) {
            if (StatisticService.sameDate(statisticFormSubmitGraph.getStatisticDate(),
                    resultStatistic.getStatisticDate(), strTimesUnit)) {
                statisticFormSubmitGraph.setNumberResponse(resultStatistic.getNumberResponse());
            }
        }
    }

    String strLabelAxisX = I18nService.getLocalizedString(PROPERTY_LABEL_AXIS_X, locale);
    String strLabelAxisY;

    if (strTypeData.equals(CONSTANT_PRODUCT_TYPE)) {
        strLabelAxisY = I18nService.getLocalizedString(PROPERTY_LABEL_AXIS_Y_PRODUCT, locale);
    } else {
        strLabelAxisY = I18nService.getLocalizedString(PROPERTY_LABEL_AXIS_Y_PURCHASE, locale);
    }

    try {
        JFreeChart chart = StatisticService.createXYGraph(listStatisticGraph, strLabelAxisX, strLabelAxisY,
                strTimesUnit);

        ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
        BufferedImage chartImage = chart.createBufferedImage(600, 200, info);
        response.setContentType(CONTENT_TYPE_IMAGE_PNG);

        PngEncoder encoder = new PngEncoder(chartImage, false, 0, 9);
        response.getOutputStream().write(encoder.pngEncode());
        response.getOutputStream().flush();
        response.getOutputStream().close();
    } catch (Exception e) {
        AppLogService.error(e);
    }
}

From source file:ch.agent.crnickl.demo.stox.Chart.java

private void saveChartAsPNG(JFreeChart chart, String fileName, int width, int height) throws KeyedException {
    OutputStream out = null;/*from  www  .  j  av a2 s. c  o m*/
    try {
        out = new BufferedOutputStream(new FileOutputStream(fileName));
        BufferedImage bufferedImage = chart.createBufferedImage(width, height, null);
        ImageEncoder imageEncoder = ImageEncoderFactory.newInstance("png");
        imageEncoder.encode(bufferedImage, out);
    } catch (Exception e) {
        throw K.JFC_OUTPUT_ERR.exception(e, fileName);
    } finally {
        try {
            if (out != null)
                out.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}