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:probe.com.view.body.quantdatasetsoverview.quantproteinstabsheet.studies.ProteinStudyComparisonScatterPlotLayout.java

private String saveToFile(final JFreeChart chart, final double width, final double height,
        ChartRenderingInfo chartRenderingInfo) {
    byte imageData[];
    try {/*  w  w  w  .j a  va2s  .  co  m*/
        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.operamasks.faces.render.graph.ChartRenderer.java

protected void encodeChartImage(FacesContext context, UIChart component, JFreeChart chart) throws IOException {
    int width = component.getWidth();
    int height = component.getHeight();
    ChartRenderingInfo info = null;//from   ww  w .j a v  a  2 s .c o m

    if (component.isShowItemTips()) {
        info = new ChartRenderingInfo();
    }

    BufferedImage image = chart.createBufferedImage(width, height, info);
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    ImageIO.write(image, "PNG", stream);
    byte[] data = stream.toByteArray();

    ChartKeeper keeper = ChartKeeper.getInstance(context);
    String filename = keeper.save(data, ".png");

    ResourceManager rm = ResourceManager.getInstance(context);
    String url = rm.getServiceResourceURL("chart", filename);

    if (isAjaxResponse(context)) {
        AjaxResponseWriter out = (AjaxResponseWriter) context.getResponseWriter();
        out.writeAttributeScript(component.getClientId(context), "src", url);
    } else {
        ResponseWriter out = context.getResponseWriter();
        out.startElement("img", component);
        out.writeAttribute("id", component.getClientId(context), "clientId");
        out.writeURIAttribute("src", url, null);
        renderPassThruAttributes(out, component);
        out.endElement("img");
    }

    if (info != null) {
        encodeItemTips(context, component, info);
    }
}

From source file:probe.com.view.body.quantdatasetsoverview.diseasegroupsfilters.ComparisonsSelectionOverviewBubbleChart.java

private String saveToFile(final JFreeChart chart, final double width, final double height) {
    chart.getXYPlot().setNoDataMessage((int) width + "," + (int) height);
    isNewImge = true;/*from w w  w  .  jav a2  s . c om*/
    Set<SquaredDot> set = new TreeSet<SquaredDot>();
    Set<SquaredDot> updatedselectedComponents = new HashSet<SquaredDot>();

    try {
        if (width < 1 || height < 1) {
            return "";
        }

        imageData = ChartUtilities
                .encodeAsPNG(chart.createBufferedImage((int) width, (int) height, chartRenderingInfo));
        chartLayout.removeAllComponents();

        for (int i = 0; i < chartRenderingInfo.getEntityCollection().getEntityCount(); i++) {
            ChartEntity entity = chartRenderingInfo.getEntityCollection().getEntity(i);
            if (entity instanceof XYItemEntity) {
                XYItemEntity catEnt = (XYItemEntity) entity;
                SquaredDot square = new SquaredDot("cycle");
                String[] coords = catEnt.getShapeCoords().split(",");
                int smallX = Integer.MAX_VALUE;
                int largeX = Integer.MIN_VALUE;
                int smallY = Integer.MAX_VALUE;
                int largeY = Integer.MIN_VALUE;
                for (int x = 0; x < coords.length; x++) {
                    String coorX = coords[x++];
                    if (Integer.valueOf(coorX) < smallX) {
                        smallX = Integer.valueOf(coorX);
                    }
                    if (Integer.valueOf(coorX) > largeX) {
                        largeX = Integer.valueOf(coorX);
                    }

                    String coorY = coords[x];
                    if (Integer.valueOf(coorY) < smallY) {
                        smallY = Integer.valueOf(coorY);

                    }
                    if (Integer.valueOf(coorY) > largeY) {
                        largeY = Integer.valueOf(coorY);
                    }

                }
                int sqheight = (largeY - smallY);
                if (sqheight < 2) {
                    continue;
                } else if (sqheight < 14) {
                    smallY = smallY - (14 - sqheight);
                }

                int sqwidth = (largeX - smallX);
                int finalWidth;
                if (sqwidth < 20) {
                    finalWidth = 20;
                    smallX = smallX - ((finalWidth - sqwidth) / 2);

                } else {
                    finalWidth = sqwidth;
                }
                int finalHeight;

                if (sqheight < 20) {
                    finalHeight = 20;
                    if (sqheight < 14) {
                        smallY = smallY - (((finalHeight - sqheight) / 2) - (14 - sqheight));
                    } else {
                        smallY = smallY - ((finalHeight - sqheight) / 2);
                    }

                } else {
                    finalHeight = sqheight;
                }
                square.setWidth((finalWidth + 2) + "px");
                square.setHeight((finalHeight + 2) + "px");
                if (selectedComparisonList == null || selectedComparisonList.isEmpty()) {
                    return "";
                }
                QuantDiseaseGroupsComparison comparison;
                if (userCustomizedComparison != null && catEnt.getSeriesIndex() == 0) {
                    continue;
                } else if (userCustomizedComparison != null && catEnt.getSeriesIndex() == 1) {
                    comparison = userCustomizedComparison;
                } else {
                    comparison = ((QuantDiseaseGroupsComparison) selectedComparisonList
                            .toArray()[catEnt.getSeriesIndex() - 1 - userDataCounter]);
                }

                String header = comparison.getComparisonHeader();
                String updatedHeader = comparison.getComparisonFullName();//header.split(" / ")[0].split("\n")[0] + " / " + header.split(" / ")[1].split("\n")[0] + " - " + header.split(" / ")[1].split("\n")[1].replace("_", " ").replace("-", "'").replace("Disease", "") + "";
                int itemNumber = (int) ((XYItemEntity) entity).getDataset()
                        .getYValue(((XYItemEntity) entity).getSeriesIndex(), ((XYItemEntity) entity).getItem());

                square.setDescription(
                        updatedHeader + "<br/>#Proteins " + (int) tooltipsProtNumberMap.get(header)[itemNumber]
                                + " " + tooltipLabels[itemNumber]);
                double categIndex = (double) itemNumber;
                int seriesIndex = ((XYItemEntity) entity).getSeriesIndex();
                square.setParam("seriesIndex", seriesIndex);
                square.setParam("categIndex", categIndex);

                if (!lastselectedComponents.isEmpty()) {
                    square.unselect();
                    for (SquaredDot lastselectedComponent : lastselectedComponents) {
                        if (lastselectedComponent != null
                                && categIndex == (Double) lastselectedComponent.getParam("categIndex")
                                && seriesIndex == (Integer) lastselectedComponent.getParam("seriesIndex")) {
                            square.select();
                            updatedselectedComponents.add(square);
                            break;
                        }
                    }

                }

                square.setParam("position", "left: " + (smallX - 1) + "px; top: " + (smallY - 1) + "px;");
                set.add(square);
            }

        }
        lastselectedComponents.clear();
        lastselectedComponents.addAll(updatedselectedComponents);
        for (SquaredDot square : set) {
            chartLayout.addComponent(square, square.getParam("position").toString());
        }
        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:fr.paris.lutece.plugins.form.web.DoDownloadGraph.java

/**
 * Write in the http response the statistic graph of a question
 * @param request the http request//from   w w w.  j ava  2 s .c o  m
 * @param response The http response
 *
 */
public void doGenerateGraph(HttpServletRequest request, HttpServletResponse response) {
    JFreeChart chart = null;
    Plugin plugin = null;
    IEntry entry;
    GraphType graphType = null;
    int nIdEntry = -1;
    int nIdGraphType = -1;

    String strIdEntry = request.getParameter(PARAMETER_ID_ENTRY);
    String strIdGraphType = request.getParameter(PARAMETER_ID_GRAPH_TYPE);
    String strPluginName = request.getParameter(PARAMETER_PLUGIN_NAME);
    String strGraphThreeDimension = request.getParameter(PARAMETER_GRAPH_THREE_DIMENSION);
    String strGraphLabelValue = request.getParameter(PARAMETER_GRAPH_LABEL_VALUE);

    boolean nGraphThreeDimension = false;
    boolean nGraphLabelValue = false;

    if ((strGraphThreeDimension != null) && strGraphThreeDimension.equals("1")) {
        nGraphThreeDimension = true;
    }

    if ((strGraphLabelValue != null) && strGraphLabelValue.equals("1")) {
        nGraphLabelValue = true;
    }

    if ((strIdEntry != null) && !strIdEntry.equals(EMPTY_STRING) && (strIdGraphType != null)
            && !strIdGraphType.equals(EMPTY_STRING) && (strPluginName != null)
            && !strPluginName.equals(EMPTY_STRING)) {
        plugin = PluginService.getPlugin(strPluginName);

        try {
            nIdEntry = Integer.parseInt(strIdEntry);
            nIdGraphType = Integer.parseInt(strIdGraphType);
        } catch (NumberFormatException ne) {
            AppLogService.error(ne);
        }

        entry = EntryHome.findByPrimaryKey(nIdEntry, plugin);

        List<StatisticEntrySubmit> listStatistic = ResponseHome.getStatisticByIdEntry(nIdEntry, plugin);
        graphType = GraphTypeHome.findByPrimaryKey(nIdGraphType, plugin);

        if (graphType != null) {
            chart = graphType.createChart(listStatistic, entry.getTitle(), nGraphThreeDimension,
                    nGraphLabelValue);
        }

        try {
            ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
            BufferedImage chartImage = chart.createBufferedImage(600, 200, info);
            response.setContentType("image/PNG");

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

From source file:fr.paris.lutece.plugins.form.web.FormJspBean.java

/**
 * write in the http response the statistic graph of all response submit who verify the date filter
 *@param request the http request/*from w  w  w .j  a  v a 2  s  .c  o  m*/
 * @param response The http response
 *
 */
public void doGenerateGraph(HttpServletRequest request, HttpServletResponse response) {
    Plugin plugin = getPlugin();
    Locale locale = getLocale();
    ResponseFilter filter = new ResponseFilter();
    int nIdForm = -1;
    String strIdForm = request.getParameter(PARAMETER_ID_FORM);
    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);
    Timestamp tFistResponseDateFilter = null;
    Timestamp tLastResponseDateFilter = null;

    if (strFistResponseDateFilter != null) {
        tFistResponseDateFilter = FormUtils
                .getDateFirstMinute(DateUtil.formatDate(strFistResponseDateFilter, locale), locale);
    }

    if (strLastResponseDateFilter != null) {
        tLastResponseDateFilter = FormUtils
                .getDateLastMinute(DateUtil.formatDate(strLastResponseDateFilter, locale), locale);
    }

    if ((strIdForm != null) && !strIdForm.equals(EMPTY_STRING)) {
        try {
            nIdForm = Integer.parseInt(strIdForm);
        } catch (NumberFormatException ne) {
            AppLogService.error(ne);
        }
    }

    filter.setIdForm(nIdForm);
    filter.setDateFirst(tFistResponseDateFilter);
    filter.setDateLast(tLastResponseDateFilter);

    if (strTimesUnit != null) {
        if (strTimesUnit.equals(FormUtils.CONSTANT_GROUP_BY_DAY)) {
            filter.setGroupbyDay(true);
        } else if (strTimesUnit.equals(FormUtils.CONSTANT_GROUP_BY_WEEK)) {
            filter.setGroupbyWeek(true);
        } else if (strTimesUnit.equals(FormUtils.CONSTANT_GROUP_BY_MONTH)) {
            filter.setGroupbyMonth(true);
        }
    } else {
        filter.setGroupbyDay(true);
        strTimesUnit = FormUtils.CONSTANT_GROUP_BY_DAY;
    }

    List<StatisticFormSubmit> listStatisticResult = FormSubmitHome.getStatisticFormSubmit(filter, plugin);

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

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

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

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

    for (StatisticFormSubmit statisticFormSubmitGraph : listStatisticGraph) {
        for (StatisticFormSubmit statisticFormSubmitResult : listStatisticResult) {
            if (FormUtils.sameDate(statisticFormSubmitGraph.getStatisticDate(),
                    statisticFormSubmitResult.getStatisticDate(), strTimesUnit)) {
                statisticFormSubmitGraph.setNumberResponse(statisticFormSubmitResult.getNumberResponse());
            }
        }
    }

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

    JFreeChart chart = FormUtils.createXYGraph(listStatisticGraph, strLabelAxisX, strLabelAxisY, strTimesUnit);

    try {
        ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
        BufferedImage chartImage = chart.createBufferedImage(600, 200, info);
        response.setContentType("image/PNG");

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