Example usage for org.jfree.chart ChartUtilities encodeAsPNG

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

Introduction

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

Prototype

public static byte[] encodeAsPNG(BufferedImage image) throws IOException 

Source Link

Document

Encodes a BufferedImage to PNG format.

Usage

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/*w  w  w .jav  a 2s.  c o m*/
 * @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: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 {//from   ww w  .  jav  a 2s. c  o  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:web.diva.server.model.SomClustering.SomClustImgGenerator.java

public SomClustTreeSelectionResult updateUpperTreeSelection(int x, int y, double w, double h) {
    upperTreeBImg = upperTree.getImage();
    Node n = this.getNodeAt(y, x, colNode);
    SomClustTreeSelectionResult result = new SomClustTreeSelectionResult();
    if (n != null) {
        upperTree.painttree(n, upperTreeBImg.getGraphics(), Color.red);

        Stack st = new Stack();
        Vector v = new Vector();
        n.fillMembers(v, st);//from   w ww . j  a  va  2s. co  m
        int[] sel = new int[v.size()];
        for (int i = 0; i < v.size(); i++) {
            sel[i] = ((Integer) v.elementAt(i));
        }
        result.setSelectedIndices(sel);
    }
    try {
        byte[] imageData = ChartUtilities.encodeAsPNG(upperTreeBImg);
        String base64 = Base64.encodeBase64String(imageData);
        base64 = "data:image/png;base64," + base64;
        result.setTreeImg1Url(base64);

        System.gc();

        //            result.setTreeImgUrl(navgStringImg);

        return result;
    } catch (IOException e) {
        System.err.println(e.getLocalizedMessage());
    }
    return null;

}

From source file:playground.christoph.evacuation.analysis.EvacuationTimePictureWriter.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   w  w w  .ja v  a  2 s . c  o  m
 * @throws IOException
 */
private void writeChartToKmz(final String filename, final JFreeChart chart, int height, int width)
        throws IOException {
    byte[] img;
    img = ChartUtilities.encodeAsPNG(chart.createBufferedImage(height, width));
    this.kmzWriter.addNonKMLFile(img, filename);
}

From source file:ubic.gemma.web.controller.expression.experiment.ExpressionExperimentQCController.java

private boolean writeDetailedFactorAnalysis(ExpressionExperiment ee, OutputStream os) throws Exception {
    SVDValueObject svdo = svdService.getSvdFactorAnalysis(ee.getId());
    if (svdo == null)
        return false;

    if (svdo.getFactors().isEmpty() && svdo.getDates().isEmpty()) {
        return false;
    }/*from   www .j  av a2s . c  om*/
    Map<Integer, Map<Long, Double>> factorCorrelations = svdo.getFactorCorrelations();
    // Map<Integer, Map<Long, Double>> factorPvalues = svdo.getFactorPvalues();
    Map<Integer, Double> dateCorrelations = svdo.getDateCorrelations();

    assert ee.getId().equals(svdo.getId());

    ee = expressionExperimentService.thawLite(ee); // need the experimental design
    int maxWidth = 30;
    Map<Long, String> efs = this.getFactorNames(ee, maxWidth);
    Map<Long, ExperimentalFactor> efIdMap = EntityUtils
            .getIdMap(ee.getExperimentalDesign().getExperimentalFactors());
    Collection<Long> continuousFactors = new HashSet<>();
    for (ExperimentalFactor ef : ee.getExperimentalDesign().getExperimentalFactors()) {
        boolean isContinous = ExperimentalDesignUtils.isContinuous(ef);
        if (isContinous) {
            continuousFactors.add(ef.getId());
        }
    }

    /*
     * Make plots of the dates vs. PCs, factors vs. PCs.
     */
    int MAX_COMP = 3;

    Map<Long, List<JFreeChart>> charts = new LinkedHashMap<>();
    ChartFactory.setChartTheme(StandardChartTheme.createLegacyTheme());
    /*
     * FACTORS
     */
    String componentShorthand = "PC";
    for (Integer component : factorCorrelations.keySet()) {

        if (component >= MAX_COMP)
            break;
        String xaxisLabel = componentShorthand + (component + 1);

        for (Long efId : factorCorrelations.get(component).keySet()) {

            /*
             * Should not happen.
             */
            if (!efs.containsKey(efId)) {
                log.warn("No experimental factor with id " + efId);
                continue;
            }

            if (!svdo.getFactors().containsKey(efId)) {
                // this should not happen.
                continue;
            }

            boolean isCategorical = !continuousFactors.contains(efId);

            Map<Long, String> categories = new HashMap<>();

            if (isCategorical) {
                this.getCategories(efIdMap, efId, categories);
            }

            if (!charts.containsKey(efId)) {
                charts.put(efId, new ArrayList<JFreeChart>());
            }

            Double a = factorCorrelations.get(component).get(efId);
            String plotname = (efs.get(efId) == null ? "?" : efs.get(efId)) + " " + xaxisLabel; // unique?

            if (a != null && !Double.isNaN(a)) {
                String title = plotname + " " + String.format("%.2f", a);
                List<Double> values = svdo.getFactors().get(efId);
                Double[] eigenGene = this.getEigenGene(svdo, component);
                assert values.size() == eigenGene.length;

                /*
                 * Plot eigengene vs values, add correlation to the plot
                 */
                JFreeChart chart;
                if (isCategorical) {

                    /*
                     * Categorical factor
                     */

                    // use the absolute value of the correlation, since direction is arbitrary.
                    title = plotname + " " + String.format("r=%.2f", Math.abs(a));

                    DefaultMultiValueCategoryDataset dataset = new DefaultMultiValueCategoryDataset();

                    /*
                     * What this code does is organize the factor values by the groups.
                     */
                    Map<String, List<Double>> groupedValues = new TreeMap<>();
                    for (int i = 0; i < values.size(); i++) {
                        Long fvId = values.get(i).longValue();
                        String fvValue = categories.get(fvId);
                        if (fvValue == null) {
                            /*
                             * Problem ...eg gill2006fateinocean id=1748 -- missing values. We just don't plot
                             * anything for this sample.
                             */
                            continue; // is this all we need to do?
                        }
                        if (!groupedValues.containsKey(fvValue)) {
                            groupedValues.put(fvValue, new ArrayList<Double>());
                        }

                        groupedValues.get(fvValue).add(eigenGene[i]);

                        if (log.isDebugEnabled())
                            log.debug(fvValue + " " + values.get(i));
                    }

                    for (String key : groupedValues.keySet()) {
                        dataset.add(groupedValues.get(key), plotname, key);
                    }

                    // don't show the name of the X axis: it's redundant with the title.
                    NumberAxis rangeAxis = new NumberAxis(xaxisLabel);
                    rangeAxis.setAutoRangeIncludesZero(false);
                    // rangeAxis.setAutoRange( false );
                    rangeAxis.setAutoRangeMinimumSize(4.0);
                    // rangeAxis.setRange( new Range( -2, 2 ) );

                    CategoryPlot plot = new CategoryPlot(dataset, new CategoryAxis(null), rangeAxis,
                            new ScatterRenderer());
                    plot.setRangeGridlinesVisible(false);
                    plot.setDomainGridlinesVisible(false);

                    chart = new JFreeChart(title, new Font("SansSerif", Font.BOLD, 12), plot, false);

                    ScatterRenderer renderer = (ScatterRenderer) plot.getRenderer();
                    float saturationDrop = (float) Math.min(1.0, component * 0.8f / MAX_COMP);
                    renderer.setSeriesFillPaint(0, Color.getHSBColor(0.0f, 1.0f - saturationDrop, 0.7f));
                    renderer.setSeriesShape(0, new Ellipse2D.Double(0, 0, 3, 3));
                    renderer.setUseOutlinePaint(false);
                    renderer.setUseFillPaint(true);
                    renderer.setBaseFillPaint(Color.white);
                    CategoryAxis domainAxis = plot.getDomainAxis();
                    domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);
                } else {

                    /*
                     * Continuous value factor
                     */

                    DefaultXYDataset series = new DefaultXYDataset();
                    series.addSeries(plotname,
                            new double[][] { ArrayUtils.toPrimitive(values.toArray(new Double[] {})),
                                    ArrayUtils.toPrimitive(eigenGene) });

                    // don't show x-axis label, which would otherwise be efs.get( efId )
                    chart = ChartFactory.createScatterPlot(title, null, xaxisLabel, series,
                            PlotOrientation.VERTICAL, false, false, false);
                    XYPlot plot = chart.getXYPlot();
                    plot.setRangeGridlinesVisible(false);
                    plot.setDomainGridlinesVisible(false);

                    XYItemRenderer renderer = plot.getRenderer();
                    renderer.setBasePaint(Color.white);
                    renderer.setSeriesShape(0, new Ellipse2D.Double(0, 0, 3, 3));
                    float saturationDrop = (float) Math.min(1.0, component * 0.8f / MAX_COMP);
                    renderer.setSeriesPaint(0, Color.getHSBColor(0.0f, 1.0f - saturationDrop, 0.7f));
                    plot.setRenderer(renderer);
                }

                chart.getTitle().setFont(new Font("SansSerif", Font.BOLD, 12));

                charts.get(efId).add(chart);
            }
        }
    }

    /*
     * DATES
     */
    charts.put(-1L, new ArrayList<JFreeChart>());
    for (Integer component : dateCorrelations.keySet()) {
        String xaxisLabel = componentShorthand + (component + 1);

        List<Date> dates = svdo.getDates();
        if (dates.isEmpty())
            break;

        long secspan = ubic.basecode.util.DateUtil.numberOfSecondsBetweenDates(dates);

        if (component >= MAX_COMP)
            break;
        Double a = dateCorrelations.get(component);

        if (a != null && !Double.isNaN(a)) {
            Double[] eigenGene = svdo.getvMatrix().getColObj(component);

            /*
             * Plot eigengene vs values, add correlation to the plot
             */
            TimeSeries series = new TimeSeries("Dates vs. eigen" + (component + 1));
            int i = 0;
            for (Date d : dates) {
                // if span is less than an hour, retain the minute.
                if (secspan < 60 * 60) {
                    series.addOrUpdate(new Minute(d), eigenGene[i++]);
                } else {
                    series.addOrUpdate(new Hour(d), eigenGene[i++]);
                }

            }
            TimeSeriesCollection dataset = new TimeSeriesCollection();
            dataset.addSeries(series);

            JFreeChart chart = ChartFactory.createTimeSeriesChart(
                    "Dates: " + xaxisLabel + " " + String.format("r=%.2f", a), null, xaxisLabel, dataset, false,
                    false, false);

            XYPlot xyPlot = chart.getXYPlot();

            chart.getTitle().setFont(new Font("SansSerif", Font.BOLD, 12));

            // standard renderer makes lines.
            XYDotRenderer renderer = new XYDotRenderer();
            renderer.setBaseFillPaint(Color.white);
            renderer.setDotHeight(3);
            renderer.setDotWidth(3);
            renderer.setSeriesShape(0, new Ellipse2D.Double(0, 0, 3, 3)); // has no effect, need dotheight.
            float saturationDrop = (float) Math.min(1.0, component * 0.8f / MAX_COMP);
            renderer.setSeriesPaint(0, Color.getHSBColor(0.0f, 1.0f - saturationDrop, 0.7f));
            ValueAxis domainAxis = xyPlot.getDomainAxis();
            domainAxis.setVerticalTickLabels(true);
            xyPlot.setRenderer(renderer);
            xyPlot.setRangeGridlinesVisible(false);
            xyPlot.setDomainGridlinesVisible(false);
            charts.get(-1L).add(chart);

        }
    }

    /*
     * Plot in a grid, with each factor as a column. FIXME What if we have too many factors to fit on the screen?
     */
    int columns = (int) Math.ceil(charts.size());
    int perChartSize = ExpressionExperimentQCController.DEFAULT_QC_IMAGE_SIZE_PX;
    BufferedImage image = new BufferedImage(columns * perChartSize, MAX_COMP * perChartSize,
            BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2 = image.createGraphics();
    int currentX = 0;
    int currentY = 0;
    for (Long id : charts.keySet()) {
        for (JFreeChart chart : charts.get(id)) {
            this.addChartToGraphics(chart, g2, currentX, currentY, perChartSize, perChartSize);
            if (currentY + perChartSize < MAX_COMP * perChartSize) {
                currentY += perChartSize;
            } else {
                currentY = 0;
                currentX += perChartSize;
            }
        }
    }

    os.write(ChartUtilities.encodeAsPNG(image));
    return true;
}

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;//  www . j  a  v  a 2  s.  c  o m
    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:probe.com.view.body.quantdatasetsoverview.diseasegroupsfilters.ComparisonsSelectionOverviewBubbleChart.java

public String getChartThumbImage() {
    if (chart == null) {
        return null;
    }/*ww w . j ava2  s. c  o  m*/
    XYPlot xyplot = chart.getXYPlot();
    xyplot.getDomainAxis().setVisible(false);
    xyplot.getRangeAxis().setVisible(false);
    chart.setBorderVisible(true);
    chart.setBorderPaint(Color.LIGHT_GRAY);
    String base64 = "";
    try {
        base64 = Base64.encodeBase64String(ChartUtilities.encodeAsPNG(chart.createBufferedImage(200, 200)));
    } catch (IOException ex) {
        Logger.getLogger(ComparisonsSelectionOverviewBubbleChart.class.getName()).log(Level.SEVERE, null, ex);
    }

    base64 = "data:image/png;base64," + base64;

    chart.setBorderVisible(false);
    xyplot.getDomainAxis().setVisible(true);
    xyplot.getRangeAxis().setVisible(true);

    //        styles.add(".matrixbtn  { background-image: url(" + base64 + " )!important;}");
    return base64;

}