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

Source Link

Document

Writes a chart to an output stream in PNG format.

Usage

From source file:org.posterita.core.AbstractChart.java

public void writeChartAsPNG(OutputStream outputStream, int width, int height) throws OperationException {
    try {//from ww  w  .j  a v a2s.co  m
        ChartUtilities.writeChartAsPNG(outputStream, getChart(), width, height, renderingInfo);
    } catch (IOException e) {
        throw new OperationException("Problem occured while write chart.", e);
    }
}

From source file:org.sakaiproject.gradebookng.tool.component.JFreeChartImageWithToolTip.java

@Override
protected IResource getImageResource() {
    IResource imageResource = null;/*from  w w w.  j a va  2s  .  c  o m*/
    final JFreeChart chart = (JFreeChart) getDefaultModelObject();
    imageResource = new DynamicImageResource() {
        private static final long serialVersionUID = 1L;

        @Override
        protected byte[] getImageData(final Attributes attributes) {
            final ByteArrayOutputStream stream = new ByteArrayOutputStream();
            try {
                if (chart != null) {
                    JFreeChartImageWithToolTip.this.chartRenderingInfo.clear();
                    ChartUtilities.writeChartAsPNG(stream, chart, JFreeChartImageWithToolTip.this.width,
                            JFreeChartImageWithToolTip.this.height,
                            JFreeChartImageWithToolTip.this.chartRenderingInfo);
                }
            } catch (final IOException ex) {
                // TODO logging for rendering chart error
            }
            return stream.toByteArray();
        }
    };
    return imageResource;
}

From source file:servlet.SalesReportPieChart.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from w w w  . j  a v  a 2 s  .c  o  m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    DefaultPieDataset dataset = new DefaultPieDataset();
    int totalTickets = Integer.valueOf(request.getParameter("totalTickets"));
    int totalSoldTickets = Integer.valueOf(request.getParameter("totalSoldTickets"));

    dataset.setValue("Unsold Tickets", new Double(totalTickets - totalSoldTickets));
    dataset.setValue("Sold Tickets", new Double(totalSoldTickets));

    JFreeChart chart = ChartFactory.createPieChart("Ticket Sales", // chart title
            dataset, // data
            true, // include legend
            true, false);

    PiePlot plot = (PiePlot) chart.getPlot();
    plot.setSectionPaint("Unsold Tickets", Color.DARK_GRAY);
    plot.setSectionPaint("Sold Tickets", Color.CYAN);
    plot.setExplodePercent("Unsold Tickets", 0.10);
    plot.setSimpleLabels(true);
    plot.setBackgroundPaint(Color.WHITE);

    PieSectionLabelGenerator gen = new StandardPieSectionLabelGenerator("{0}: {1} ({2})",
            new DecimalFormat("0"), new DecimalFormat("0%"));
    plot.setLabelGenerator(gen);

    final ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());

    int width = 500; /* Width of the image */

    int height = 400; /* Height of the image */

    response.setContentType("image/png");
    OutputStream out = response.getOutputStream();

    ChartUtilities.writeChartAsPNG(out, chart, 400, 300, info);
}

From source file:org.pentaho.chart.plugin.jfreechart.outputs.JFreeChartOutput.java

public OutputStream persistChart(OutputStream outputStream, IOutput.OutputTypes fileType, int width, int height)
        throws PersistenceException {
    info = new ChartRenderingInfo(new StandardEntityCollection());
    if (outputStream == null) {
        outputStream = new ByteArrayOutputStream();
    }//  w ww  .  j  a v  a2s.  c o  m

    try {
        outputStream.flush();
    } catch (IOException e1) {
        throw new PersistenceException(e1);
    }
    if (fileType == IOutput.OutputTypes.FILE_TYPE_JPEG) {
        try {
            ChartUtilities.writeChartAsJPEG(outputStream, chart, width, height, info);
        } catch (IOException e) {
            throw new PersistenceException(e);
        }
    } else if ((fileType == IOutput.OutputTypes.FILE_TYPE_PNG) || (fileType == null)) {
        try {
            ChartUtilities.writeChartAsPNG(outputStream, chart, width, height, info);
        } catch (IOException e) {
            throw new PersistenceException(e);
        }
    }
    return outputStream;
}

From source file:servlet.SalesReportEventsBarChart.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   ww w  .j  a  va 2 s . com
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    List<ArrayList> data = productSession.getEventSessionNo();

    final DefaultCategoryDataset dataset = new DefaultCategoryDataset();

    for (int i = 0; i < data.size(); i++) {
        dataset.addValue(Integer.valueOf(data.get(i).get(1).toString()), "Sessions",
                data.get(i).get(0).toString());
    }

    final ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());

    JFreeChart barChart = ChartFactory.createBarChart("No of Sessions", "Event", "Sessions", dataset,
            PlotOrientation.VERTICAL, true, true, false);

    CategoryPlot cplot = (CategoryPlot) barChart.getPlot();
    cplot.setBackgroundPaint(Color.WHITE);//change background color

    //set  bar chart color
    ((BarRenderer) cplot.getRenderer()).setBarPainter(new StandardBarPainter());

    BarRenderer r = (BarRenderer) barChart.getCategoryPlot().getRenderer();
    r.setSeriesPaint(0, Color.GREEN);

    r.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator("{2}", NumberFormat.getInstance()));
    r.setBaseItemLabelsVisible(true);

    CategoryAxis categoryAxis = cplot.getDomainAxis();
    categoryAxis.setUpperMargin(0.15);

    NumberAxis rangeAxis = (NumberAxis) cplot.getRangeAxis();
    rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    rangeAxis.setUpperMargin(0.15);

    int width = 550; /* Width of the image */

    int height = 450; /* Height of the image */

    response.setContentType("image/png");
    OutputStream out = response.getOutputStream();

    ChartUtilities.writeChartAsPNG(out, barChart, 400, 300, info);

}

From source file:org.sakaiproject.gradebookng.tool.component.JFreeChartImageWithToolTip.java

@Override
public void onComponentTagBody(final MarkupStream markupStream, final ComponentTag openTag) {
    final JFreeChart chart = (JFreeChart) getDefaultModelObject();
    if (chart == null) {
        return;/*from   w w  w  . jav a2  s.c  o m*/
    }
    final ByteArrayOutputStream stream = new ByteArrayOutputStream();
    try {
        this.chartRenderingInfo.clear();
        ChartUtilities.writeChartAsPNG(stream, chart, this.width, this.height, this.chartRenderingInfo);
    } catch (final IOException ex) {
        // do something
    }
    replaceComponentTagBody(markupStream, openTag,
            ChartUtilities.getImageMap(this.imageMapId, this.chartRenderingInfo));
}

From source file:de.laures.cewolf.util.Renderer.java

/**
 * Handles rendering a chart as a PNG. Currently this method is synchronized
 * because of concurrency issues with JFreeChart.
 *
 * @param  baos/* w  w  w . j  a  va 2 s . co m*/
 * @param  chart
 * @param  width
 * @param  height
 * @param  info
 * @throws IOException
 */
private static synchronized void handlePNG(ByteArrayOutputStream baos, JFreeChart chart, int width, int height,
        ChartRenderingInfo info) throws IOException {
    ChartUtilities.writeChartAsPNG(baos, chart, width, height, info);
}

From source file:org.toobsframework.pres.chart.ChartBuilder.java

public String buildAsImage(ChartDefinition chartDef, IRequest componentRequest, int width, int height)
        throws ChartException {
    JFreeChart chart = this.build(chartDef, componentRequest);
    if (width <= 0) {
        chartDef.getChartWidth();//  ww  w.  j  a v a  2  s  .c  o m
    }
    if (height <= 0) {
        chartDef.getChartHeight();
    }

    String genFileName = chartDef.getId() + "-" + new Date().getTime() + ".png";
    String imageOutputFileName = configuration.getUploadDir() + genFileName;
    try {
        File imageOutputFile = new File(imageOutputFileName);
        OutputStream os = null;
        ChartRenderingInfo chartRenderingInfo = new ChartRenderingInfo();
        try {
            os = new FileOutputStream(imageOutputFile);
            ChartUtilities.writeChartAsPNG(os, chart, width, height, chartRenderingInfo);
        } finally {
            if (os != null) {
                os.close();
            }
        }
    } catch (FileNotFoundException e) {
        throw new ChartException(e);
    } catch (IOException e) {
        throw new ChartException(e);
    }

    return imageOutputFileName;
}

From source file:gov.nih.nci.ispy.web.taglib.CatCorrPlotTag.java

public int doStartTag() {

    ServletRequest request = pageContext.getRequest();
    HttpSession session = pageContext.getSession();
    Object o = request.getAttribute(beanName);
    JspWriter out = pageContext.getOut();
    ServletResponse response = pageContext.getResponse();

    ISPYCategoricalCorrelationFinding corrFinding = (ISPYCategoricalCorrelationFinding) businessTierCache
            .getSessionFinding(session.getId(), taskId);

    try {/*from ww  w  .  ja  v a  2s .co  m*/
        List<DataPointVector> dataSet = corrFinding.getDataVectors();
        List<ReporterInfo> reporterInfoList = corrFinding.getCatCorrRequest().getReporters();

        //get better labels for X and Y axis.
        ContinuousType ct = corrFinding.getContType();
        String xLabel, yLabel;
        if (ct == ContinuousType.GENE) {
            yLabel = "Log base 2 expression value";
        } else {
            yLabel = ct.toString();
        }

        //if there are reporters involved then send them in so that they can be used to create
        //a series.

        ISPYCategoricalCorrelationPlot plot = new ISPYCategoricalCorrelationPlot(dataSet, reporterInfoList,
                "Category", yLabel, corrFinding.getContType(), ColorByType.CLINICALRESPONSE);

        chart = plot.getChart();
        ISPYImageFileHandler imageHandler = new ISPYImageFileHandler(session.getId(), "png", 650, 600);
        //The final complete path to be used by the webapplication
        String finalPath = imageHandler.getSessionTempFolder();
        String finalURLpath = imageHandler.getFinalURLPath();
        /*
         * Create the actual charts, writing it to the session temp folder
        */
        ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
        String mapName = imageHandler.createUniqueMapName();
        //PrintWriter writer = new PrintWriter(new FileWriter(mapName));
        ChartUtilities.writeChartAsPNG(new FileOutputStream(finalPath), chart, 650, 600, info);
        //ImageMapUtil.writeBoundingRectImageMap(writer,"PCAimageMap",info,true);
        //writer.close();

        /*   This is here to put the thread into a loop while it waits for the
         *   image to be available.  It has an unsophisticated timer but at 
         *   least it is something to avoid an endless loop.
         **/
        boolean imageReady = false;
        int timeout = 1000;
        FileInputStream inputStream = null;
        while (!imageReady) {
            timeout--;
            try {
                inputStream = new FileInputStream(finalPath);
                inputStream.available();
                imageReady = true;
                inputStream.close();
            } catch (IOException ioe) {
                imageReady = false;
                if (inputStream != null) {
                    inputStream.close();
                }
            }
            if (timeout <= 1) {

                break;
            }
        }

        out.print(ImageMapUtil.getBoundingRectImageMapTag(mapName, true, info));
        finalURLpath = finalURLpath.replace("\\", "/");
        long randomness = System.currentTimeMillis(); //prevent image caching
        out.print("<img id=\"geneChart\" name=\"geneChart\" src=\"" + finalURLpath + "?" + randomness
                + "\" usemap=\"#" + mapName + "\" border=\"0\" />");

        //(imageHandler.getImageTag(mapFileName));

    } catch (IOException e) {
        logger.error(e);
    } catch (Exception e) {
        logger.error(e);
    } catch (Throwable t) {
        logger.error(t);
    }

    return EVAL_BODY_INCLUDE;
}

From source file:org.toobsframework.pres.chart.controller.ChartHandler.java

/**
 * /*from  w  ww.j a v a 2 s .  c om*/
 * Retrieves the URL path to use for lookup and delegates to
 * <code>getViewNameForUrlPath</code>.
 * 
 * @throws Exception Exception fetching or rendering component.
 * @see #getViewNameForUrlPath
 * 
 */
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response,
        UrlDispatchInfo dispatchInfo) throws Exception {

    String chartId = dispatchInfo.getResourceId();
    if (log.isDebugEnabled()) {
        log.debug("Rendering chart '" + chartId + "' for lookup path: " + dispatchInfo.getOriginalPath());
    }

    IRequest componentRequest = this.setupComponentRequest(dispatchInfo, request, response, true);

    Date startTime = null;
    if (log.isDebugEnabled()) {
        startTime = new Date();
    }

    JFreeChart chart = null;
    int height = 400;
    int width = 600;
    ChartDefinition chartDef = null;
    if (null != chartId && !chartId.equals("")) {
        try {
            request.setAttribute("chartId", chartId);
            chartDef = this.chartManager.getChartDefinition(chartId);
        } catch (ChartNotFoundException cnfe) {
            log.warn("Chart " + chartId + " not found.");
            throw cnfe;
        }
        try {

            chart = chartBuilder.build(chartDef, componentRequest);
            width = chartDef.getChartWidth();
            height = chartDef.getChartHeight();

        } catch (ChartException e) {
            Throwable t = e.rootCause();
            log.info("Root cause " + t.getClass().getName() + " " + t.getMessage());
            throw e;
        } catch (Exception e) {
            throw e;
        } finally {
            this.componentRequestManager.unset();
        }

    } else {
        throw new Exception("No chartId specified");
    }

    //Write out to the response.
    response.setHeader("Pragma", "no-cache"); // HTTP 1.0
    response.setHeader("Cache-Control", "max-age=0, must-revalidate"); // HTTP 1.1
    ChartRenderingInfo chartRenderingInfo = new ChartRenderingInfo();
    if (chartDef.doImageWithMap()) {
        response.setContentType("text/html; charset=UTF-8");
        String genFileName = chartDef.getId() + "-" + new Date().getTime() + ".png";
        String imageOutputFileName = configuration.getUploadDir() + genFileName;
        File imageOutputFile = new File(imageOutputFileName);
        OutputStream os = null;
        try {
            os = new FileOutputStream(imageOutputFile);
            ChartUtilities.writeChartAsPNG(os, chart, width, height, chartRenderingInfo);
        } finally {
            if (os != null) {
                os.close();
            }
        }
        PrintWriter writer = response.getWriter();
        StringBuffer sb = new StringBuffer();

        // TODO BUGBUG Chart location needs to fixed
        sb.append("<img id=\"chart-").append(chartDef.getId()).append("\" src=\"")
                .append(/*Configuration.getInstance().getMainContext() +*/ "/upload/" + genFileName)
                .append("\" ismap=\"ismap\" usemap=\"#").append(chartDef.getId()).append("Map\" />");
        URLTagFragmentGenerator urlGenerator;
        if (chartDef.getUrlFragmentBean() != null) {
            urlGenerator = (URLTagFragmentGenerator) beanFactory.getBean(chartDef.getUrlFragmentBean());
        } else {
            urlGenerator = new StandardURLTagFragmentGenerator();
        }
        sb.append(ImageMapUtilities.getImageMap(chartDef.getId() + "Map", chartRenderingInfo, null,
                urlGenerator));
        writer.print(sb.toString());
        writer.flush();

    } else {
        response.setContentType("image/png");

        ChartUtilities.writeChartAsPNG(response.getOutputStream(), chart, width, height, chartRenderingInfo);

    }

    if (log.isDebugEnabled()) {
        Date endTime = new Date();
        log.debug("Time [" + chartId + "] - " + (endTime.getTime() - startTime.getTime()));
    }
    return null;

}