List of usage examples for org.jfree.chart JFreeChart createBufferedImage
public BufferedImage createBufferedImage(int width, int height, int imageType, ChartRenderingInfo info)
From source file:org.jivesoftware.openfire.reporting.graph.GraphEngine.java
/** * Generates a Sparkline type graph. Sparkline graphs * are "intense, simple, wordlike graphics" so named by Edward Tufte. The big * difference between the graph produced by this method compared to the * graph produced by the <code>generateGraph</code> method is that this one * produces graphs with no x-axis and no y-axis and is usually smaller in size. * @param key// w w w . ja v a 2 s.c om * @param width * @param height * @param startTime * @param endTime * @param dataPoints * @return * @throws IOException */ public byte[] generateSparklinesGraph(String key, int width, int height, String color, long startTime, long endTime, int dataPoints) throws IOException { Statistic[] def = statsViewer.getStatistic(key); if (def == null) { return null; } JFreeChart chart; switch (def[0].getStatType()) { case count: chart = generateSparklineBarGraph(key, color, def, startTime, endTime, dataPoints); break; default: chart = generateSparklineAreaChart(key, color, def, startTime, endTime, dataPoints); } KeypointPNGEncoderAdapter encoder = new KeypointPNGEncoderAdapter(); encoder.setEncodingAlpha(true); return encoder.encode(chart.createBufferedImage(width, height, BufferedImage.BITMASK, null)); }
From source file:fr.ens.transcriptome.corsen.gui.qt.ResultGraphs.java
/** * Create a boxplot.//from w ww. ja v a 2 s. c o m * @param results Results to use * @return a QImage */ public QImage createBoxPlot(final CorsenResult results, final String unit) { this.width = this.width / 2; Map<Particle3D, Distance> distsMin = results.getMinDistances(); Map<Particle3D, Distance> distsMax = results.getMaxDistances(); if (distsMin == null || distsMax == null) return null; List<Float> listMin = new ArrayList<Float>(); List<Float> listMax = new ArrayList<Float>(); for (Map.Entry<Particle3D, Distance> e : distsMin.entrySet()) { final Particle3D p = e.getKey(); final long intensity = p.getIntensity(); final float distanceMin = e.getValue().getDistance(); final float distanceMax = distsMax.get(p).getDistance(); for (int i = 0; i < intensity; i++) { listMin.add(distanceMin); listMax.add(distanceMax); } } DefaultBoxAndWhiskerCategoryDataset defaultboxandwhiskercategorydataset = new DefaultBoxAndWhiskerCategoryDataset(); if (results.getMinAnalyser().count() > 0) defaultboxandwhiskercategorydataset .add(convertDistanceAnalyserToBoxAndWhiskerItem(results.getMinAnalyser()), "Distances", "Min"); // defaultboxandwhiskercategorydataset.add(listMin, "Distances", "Min"); // defaultboxandwhiskercategorydataset.add(listMax, "Distances", "Max"); JFreeChart chart = ChartFactory.createBoxAndWhiskerChart("Intensities Boxplot", "", "Distance" + unitLegend(unit), defaultboxandwhiskercategorydataset, false); addTransparency(chart); // CategoryPlot categoryplot = (CategoryPlot) chart.getPlot(); // // chart.setBackgroundPaint(Color.white); // categoryplot.setBackgroundPaint(Color.lightGray); // categoryplot.setDomainGridlinePaint(Color.white); // categoryplot.setDomainGridlinesVisible(true); // categoryplot.setRangeGridlinePaint(Color.white); // // NumberAxis numberaxis = (NumberAxis) categoryplot.getRangeAxis(); // numberaxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); final BufferedImage image = chart.createBufferedImage(this.width, this.height, BufferedImage.TYPE_INT_ARGB, null); return new QImage(toByte(image.getData().getDataBuffer()), this.width, this.height, QImage.Format.Format_ARGB32); }
From source file:lucee.runtime.tag.Chart.java
private void copy(OutputStream os, JFreeChart jfc, ChartRenderingInfo info) throws ApplicationException, IOException, ExpressionException { //OutputStream os = null; try {/* w w w. j av a2 s. c om*/ //os = res.getOutputStream(); BufferedImage bi; if (format == FORMAT_JPG) { bi = jfc.createBufferedImage(chartwidth, chartheight, BufferedImage.TYPE_INT_RGB, info); } else { bi = jfc.createBufferedImage(chartwidth, chartheight, info); } Image img; // add border if (showborder) { try { img = new Image(bi); img.addBorder(1, Color.BLACK, Image.BORDER_TYPE_CONSTANT); bi = img.getBufferedImage(); } catch (PageException e) { } } if (format == FORMAT_PNG) ChartUtilities.writeBufferedImageAsPNG(os, bi); else if (format == FORMAT_JPG) ChartUtilities.writeBufferedImageAsJPEG(os, bi); else if (format == FORMAT_GIF) { img = new lucee.runtime.img.Image(bi); img.writeOut(os, "gif", 1, true); //throw new ApplicationException("format gif not supported"); } else if (format == FORMAT_FLASH) throw new ApplicationException("format flash not supported"); } finally { IOUtil.flushEL(os); IOUtil.closeEL(os); } }
From source file:org.pentaho.di.ui.spoon.trans.TransPerfDelegate.java
private void updateCanvas() { Rectangle bounds = canvas.getBounds(); if (bounds.width <= 0 || bounds.height <= 0) { return;/*www . j a v a 2 s .c om*/ } // The list of snapshots : convert to JFreeChart dataset // DefaultCategoryDataset dataset = new DefaultCategoryDataset(); String[] selectedSteps = stepsList.getSelection(); if (selectedSteps == null || selectedSteps.length == 0) { selectedSteps = new String[] { steps[0], }; // first step stepsList.select(0); } int[] dataIndices = dataList.getSelectionIndices(); if (dataIndices == null || dataIndices.length == 0) { dataIndices = new int[] { DATA_CHOICE_WRITTEN, }; dataList.select(0); } boolean multiStep = stepsList.getSelectionCount() > 1; boolean multiData = dataList.getSelectionCount() > 1; boolean calcMoving = !multiStep && !multiData; // A single metric shown for a single step List<Double> movingList = new ArrayList<Double>(); int movingSize = 10; double movingTotal = 0; int totalTimeInSeconds = 0; for (int t = 0; t < selectedSteps.length; t++) { String stepNameCopy = selectedSteps[t]; List<StepPerformanceSnapShot> snapShotList = stepPerformanceSnapShots.get(stepNameCopy); if (snapShotList != null && snapShotList.size() > 1) { totalTimeInSeconds = (int) Math .round(((double) (snapShotList.get(snapShotList.size() - 1).getDate().getTime() - snapShotList.get(0).getDate().getTime())) / 1000); for (int i = 0; i < snapShotList.size(); i++) { StepPerformanceSnapShot snapShot = snapShotList.get(i); if (snapShot.getTimeDifference() != 0) { double factor = (double) 1000 / (double) snapShot.getTimeDifference(); for (int d = 0; d < dataIndices.length; d++) { String dataType; if (multiStep) { dataType = stepNameCopy; } else { dataType = dataChoices[dataIndices[d]]; } String xLabel = Integer.toString(Math.round(i * timeDifference / 1000)); Double metric = null; switch (dataIndices[d]) { case DATA_CHOICE_INPUT: metric = snapShot.getLinesInput() * factor; break; case DATA_CHOICE_OUTPUT: metric = snapShot.getLinesOutput() * factor; break; case DATA_CHOICE_READ: metric = snapShot.getLinesRead() * factor; break; case DATA_CHOICE_WRITTEN: metric = snapShot.getLinesWritten() * factor; break; case DATA_CHOICE_UPDATED: metric = snapShot.getLinesUpdated() * factor; break; case DATA_CHOICE_REJECTED: metric = snapShot.getLinesRejected() * factor; break; case DATA_CHOICE_INPUT_BUFFER_SIZE: metric = (double) snapShot.getInputBufferSize(); break; case DATA_CHOICE_OUTPUT_BUFFER_SIZE: metric = (double) snapShot.getOutputBufferSize(); break; default: break; } if (metric != null) { dataset.addValue(metric, dataType, xLabel); if (calcMoving) { movingTotal += metric; movingList.add(metric); if (movingList.size() > movingSize) { movingTotal -= movingList.get(0); movingList.remove(0); } double movingAverage = movingTotal / movingList.size(); dataset.addValue(movingAverage, dataType + "(Avg)", xLabel); // System.out.println("moving average = "+movingAverage+", movingTotal="+movingTotal+", m"); } } } } } } } String chartTitle = title; if (multiStep) { chartTitle += " (" + dataChoices[dataIndices[0]] + ")"; } else { chartTitle += " (" + selectedSteps[0] + ")"; } final JFreeChart chart = ChartFactory.createLineChart(chartTitle, // chart title BaseMessages.getString(PKG, "StepPerformanceSnapShotDialog.TimeInSeconds.Label", Integer.toString(totalTimeInSeconds), Long.toString(timeDifference)), // domain axis label BaseMessages.getString(PKG, "StepPerformanceSnapShotDialog.RowsPerSecond.Label"), // range axis label dataset, // data PlotOrientation.VERTICAL, // orientation true, // include legend true, // tooltips false); // urls chart.setBackgroundPaint(Color.white); TextTitle title = new TextTitle(chartTitle); // title.setExpandToFitSpace(true); // org.eclipse.swt.graphics.Color pentahoColor = GUIResource.getInstance().getColorPentaho(); // java.awt.Color color = new java.awt.Color(pentahoColor.getRed(), pentahoColor.getGreen(),pentahoColor.getBlue()); // title.setBackgroundPaint(color); title.setFont(new java.awt.Font("SansSerif", java.awt.Font.BOLD, 12)); chart.setTitle(title); CategoryPlot plot = (CategoryPlot) chart.getPlot(); plot.setBackgroundPaint(Color.white); plot.setForegroundAlpha(0.5f); plot.setRangeGridlinesVisible(true); NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis(); rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); CategoryAxis domainAxis = plot.getDomainAxis(); domainAxis.setTickLabelsVisible(false); // Customize the renderer... // LineAndShapeRenderer renderer = (LineAndShapeRenderer) plot.getRenderer(); renderer.setBaseShapesVisible(true); renderer.setDrawOutlines(true); renderer.setUseFillPaint(true); renderer.setBaseFillPaint(Color.white); renderer.setSeriesStroke(0, new BasicStroke(1.5f)); renderer.setSeriesOutlineStroke(0, new BasicStroke(1.5f)); renderer.setSeriesStroke(1, new BasicStroke(2.5f)); renderer.setSeriesOutlineStroke(1, new BasicStroke(2.5f)); renderer.setSeriesShape(0, new Ellipse2D.Double(-3.0, -3.0, 6.0, 6.0)); BufferedImage bufferedImage = chart.createBufferedImage(bounds.width, bounds.height, BufferedImage.TYPE_INT_RGB, null); ImageData imageData = ImageUtil.convertToSWT(bufferedImage); // dispose previous image... // if (image != null) { image.dispose(); } image = new Image(transGraph.getDisplay(), imageData); // Draw the image on the canvas... // canvas.redraw(); }
From source file:com.igalia.java.zk.components.JFreeChartEngine.java
public byte[] drawChart(Object data) { Chart chart = (Chart) data;/*w w w . j ava 2 s . c o m*/ ChartImpl impl = getChartImpl(chart); JFreeChart jfchart = impl.createChart(chart); Plot plot = (Plot) jfchart.getPlot(); float alpha = (float) (((float) chart.getFgAlpha()) / 255); plot.setForegroundAlpha(alpha); alpha = (float) (((float) chart.getBgAlpha()) / 255); plot.setBackgroundAlpha(alpha); int[] bgRGB = chart.getBgRGB(); if (bgRGB != null) { plot.setBackgroundPaint(new Color(bgRGB[0], bgRGB[1], bgRGB[2], chart.getBgAlpha())); } int[] paneRGB = chart.getPaneRGB(); if (paneRGB != null) { jfchart.setBackgroundPaint(new Color(paneRGB[0], paneRGB[1], paneRGB[2], chart.getPaneAlpha())); } //since 3.6.3, JFreeChart 1.0.13 change default fonts which does not support Chinese, allow //developer to set font. //title font final Font tfont = chart.getTitleFont(); if (tfont != null) { jfchart.getTitle().setFont(tfont); } //legend font final Font lfont = chart.getLegendFont(); if (lfont != null) { jfchart.getLegend().setItemFont(lfont); } if (plot instanceof CategoryPlot) { final CategoryPlot cplot = (CategoryPlot) plot; cplot.setRangeGridlinePaint(new Color(0xc0, 0xc0, 0xc0)); //Domain axis(x axis) final Font xlbfont = chart.getXAxisFont(); final Font xtkfont = chart.getXAxisTickFont(); if (xlbfont != null) { cplot.getDomainAxis().setLabelFont(xlbfont); } if (xtkfont != null) { cplot.getDomainAxis().setTickLabelFont(xtkfont); } Color[] colorMappings = (Color[]) chart.getAttribute("series-color-mappings"); if (colorMappings != null) { for (int ii = 0; ii < colorMappings.length; ii++) { cplot.getRenderer().setSeriesPaint(ii, colorMappings[ii]); } } Double lowerBound = (Double) chart.getAttribute("range-axis-lower-bound"); if (lowerBound != null) { cplot.getRangeAxis().setAutoRange(false); cplot.getRangeAxis().setLowerBound(lowerBound); } Double upperBound = (Double) chart.getAttribute("range-axis-upper-bound"); if (upperBound != null) { cplot.getRangeAxis().setAutoRange(false); cplot.getRangeAxis().setUpperBound(upperBound); } //Range axis(y axis) final Font ylbfont = chart.getYAxisFont(); final Font ytkfont = chart.getYAxisTickFont(); if (ylbfont != null) { cplot.getRangeAxis().setLabelFont(ylbfont); } if (ytkfont != null) { cplot.getRangeAxis().setTickLabelFont(ytkfont); } } else if (plot instanceof XYPlot) { final XYPlot xyplot = (XYPlot) plot; xyplot.setRangeGridlinePaint(Color.LIGHT_GRAY); xyplot.setDomainGridlinePaint(Color.LIGHT_GRAY); //Domain axis(x axis) final Font xlbfont = chart.getXAxisFont(); final Font xtkfont = chart.getXAxisTickFont(); if (xlbfont != null) { xyplot.getDomainAxis().setLabelFont(xlbfont); } if (xtkfont != null) { xyplot.getDomainAxis().setTickLabelFont(xtkfont); } //Range axis(y axis) final Font ylbfont = chart.getYAxisFont(); final Font ytkfont = chart.getYAxisTickFont(); if (ylbfont != null) { xyplot.getRangeAxis().setLabelFont(ylbfont); } if (ytkfont != null) { xyplot.getRangeAxis().setTickLabelFont(ytkfont); } } else if (plot instanceof PiePlot) { plot.setOutlineStroke(null); } //callbacks for each area ChartRenderingInfo jfinfo = new ChartRenderingInfo(); BufferedImage bi = jfchart.createBufferedImage(chart.getIntWidth(), chart.getIntHeight(), Transparency.TRANSLUCENT, jfinfo); //remove old areas if (chart.getChildren().size() > 20) chart.invalidate(); //improve performance if too many chart chart.getChildren().clear(); if (Events.isListened(chart, Events.ON_CLICK, false) || chart.isShowTooltiptext()) { int j = 0; String preUrl = null; for (Iterator it = jfinfo.getEntityCollection().iterator(); it.hasNext();) { ChartEntity ce = (ChartEntity) it.next(); final String url = ce.getURLText(); //workaround JFreeChart's bug (skip replicate areas) if (url != null) { if (preUrl == null) { preUrl = url; } else if (url.equals(preUrl)) { //start replicate, skip break; } } //1. JFreeChartEntity area cover the whole chart, will "mask" other areas //2. LegendTitle area cover the whole legend, will "mask" each legend //3. PlotEntity cover the whole chart plotting araa, will "mask" each bar/line/area if (!(ce instanceof JFreeChartEntity) && !(ce instanceof TitleEntity && ((TitleEntity) ce).getTitle() instanceof LegendTitle) && !(ce instanceof PlotEntity)) { Area area = new Area(); area.setParent(chart); area.setCoords(ce.getShapeCoords()); area.setShape(ce.getShapeType()); area.setId("area_" + chart.getId() + '_' + (j++)); if (chart.isShowTooltiptext() && ce.getToolTipText() != null) { area.setTooltiptext(ce.getToolTipText()); } area.setAttribute("url", ce.getURLText()); impl.render(chart, area, ce); if (chart.getAreaListener() != null) { try { chart.getAreaListener().onRender(area, ce); } catch (Exception ex) { throw UiException.Aide.wrap(ex); } } } } } //clean up the "LEGEND_SEQ" //used for workaround LegendItemEntity.getSeries() always return 0 //used for workaround TickLabelEntity no information chart.removeAttribute("LEGEND_SEQ"); chart.removeAttribute("TICK_SEQ"); try { //encode into png image format byte array return EncoderUtil.encode(bi, ImageFormat.PNG, true); } catch (java.io.IOException ex) { throw UiException.Aide.wrap(ex); } }