List of usage examples for org.jfree.chart ChartUtilities writeChartAsPNG
public static void writeChartAsPNG(OutputStream out, JFreeChart chart, int width, int height) throws IOException
From source file:org.gaixie.micrite.struts2.jfreechart.ChartResult.java
/** * Executes the result. Writes the given chart as a PNG or JPG to the servlet output stream. * * @param invocation an encapsulation of the action execution state. * @throws Exception if an error occurs when creating or writing the chart to the servlet output stream. *///from www . j a v a2 s . com public void execute(ActionInvocation invocation) throws Exception { if (!chartSet) // if our chart hasn't been set (by the testcase), we'll look it up in the value stack chart = (JFreeChart) invocation.getStack().findValue(value, JFreeChart.class); if (chart == null) // we need to have a chart object - if not, blow up throw new NullPointerException("No JFreeChart object found on the stack with name " + value); // make sure we have some value for the width and height if (height == null) throw new NullPointerException("No height parameter was given."); if (width == null) throw new NullPointerException("No width parameter was given."); // get a reference to the servlet output stream to write our chart image to OutputStream os = ServletActionContext.getResponse().getOutputStream(); try { // check the type to see what kind of output we have to produce if ("png".equalsIgnoreCase(type)) ChartUtilities.writeChartAsPNG(os, chart, width, height); else if ("jpg".equalsIgnoreCase(type) || "jpeg".equalsIgnoreCase(type)) ChartUtilities.writeChartAsJPEG(os, chart, width, height); else throw new IllegalArgumentException( type + " is not a supported render type (only JPG and PNG are)."); } finally { if (os != null) os.flush();//pw.close(); } }
From source file:net.sqs2.omr.result.export.chart.ChartImageWriter.java
public void saveBarChart(OutputStream outputStream, String categoryAxisLabel, String valueAxisLabel, DefaultCategoryDataset dataSet) { String title = ""; boolean legend = false; boolean tooltips = true; boolean urls = false; JFreeChart chart = ChartFactory.createBarChart(title, categoryAxisLabel, valueAxisLabel, dataSet, PlotOrientation.HORIZONTAL, legend, tooltips, urls); CategoryPlot plot = chart.getCategoryPlot(); setSectionPaint(dataSet, plot);/*from w w w . j a v a2s.co m*/ try { ChartUtilities.writeChartAsPNG(outputStream, chart, this.width, this.height); } catch (IOException ex) { ex.printStackTrace(); } }
From source file:org.lsug.quota.web.internal.portlet.SiteConfigurationQuotaWebPortlet.java
@Override public void serveResource(ResourceRequest resourceRequest, ResourceResponse resourceResponse) throws IOException, PortletException { StringBundler sb = new StringBundler(5); JFreeChart jFreeChart = null;/*w ww . ja v a 2s . c o m*/ DefaultPieDataset pieDataset = new DefaultPieDataset(); try { long groupId = PortalUtil.getScopeGroupId(resourceRequest); Group group = _groupLocalService.getGroup(groupId); long classNameId = 0; if (QuotaUtil.isValidGroupQuota(group)) { classNameId = group.getClassNameId(); if (group.isStagingGroup()) { groupId = group.getLiveGroupId(); } } Quota siteQuota = _quotaLocalService.getQuotaByClassNameIdClassPK(classNameId, groupId); ResourceBundle resourceBundle = ResourceBundleUtil.getBundle("content.Language", resourceRequest.getLocale(), getClass()); if (siteQuota.isEnabled()) { pieDataset.setValue(LanguageUtil.get(resourceBundle, "used-space"), siteQuota.getQuotaUsedPercentage()); pieDataset.setValue(LanguageUtil.get(resourceBundle, "unused-space"), 100 - siteQuota.getQuotaUsedPercentage()); } sb.append(LanguageUtil.get(resourceBundle, "sites-quota-enabled-sites-used-diagram-title")); jFreeChart = getCurrentSizeJFreeChart(sb.toString(), pieDataset); resourceResponse.setContentType(ContentTypes.IMAGE_PNG); OutputStream outputStream = null; try { outputStream = resourceResponse.getPortletOutputStream(); ChartUtilities.writeChartAsPNG(outputStream, jFreeChart, 400, 200); } finally { if (outputStream != null) { outputStream.close(); } } } catch (Exception e) { LOGGER.error(e); throw new PortletException(e); } }
From source file:eu.planets_project.tb.impl.chart.ExperimentChartServlet.java
/** * Process a GET request.//from w w w. j a v a2 s .c om * * @param request the request. * @param response the response. * * @throws ServletException if there is a servlet related problem. * @throws IOException if there is an I/O problem. */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { OutputStream out = response.getOutputStream(); try { String type = request.getParameter("type"); String format = request.getParameter("format"); String eid = request.getParameter("eid"); JFreeChart chart = null; if ("pie".equalsIgnoreCase(type)) { chart = createPieChart(); } else if ("bar".equalsIgnoreCase(type)) { chart = createBarChart(); } else if ("time".equalsIgnoreCase(type)) { chart = createTimeSeriesChart(); } else if ("exp".equalsIgnoreCase(type)) { chart = createXYChart(eid); } else if ("wall".equalsIgnoreCase(type)) { chart = createWallclockChart(eid); } else { chart = null; } // Render if (chart != null) { if ("svg".equalsIgnoreCase(format)) { response.setContentType("image/svg+xml"); writeChartAsSVG(out, chart, 600, 500); } else { response.setContentType("image/png"); // force aliasing of the rendered content.. chart.getRenderingHints().put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); ChartUtilities.writeChartAsPNG(out, chart, 600, 500); } } } catch (Exception e) { System.err.println(e.toString()); e.printStackTrace(); } finally { out.close(); } }
From source file:edu.fullerton.viewerplugin.PluginSupport.java
/** * Create an image from the Chart Panel and add it the database * @param cp input plot// w w w .j av a 2 s . c o m * @return image ID of newly added row * @throws IOException * @throws SQLException * @throws NoSuchAlgorithmException */ public int saveImageAsPNG(ChartPanel cp) throws IOException, SQLException, NoSuchAlgorithmException { JFreeChart chart = cp.getChart(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ChartUtilities.writeChartAsPNG(bos, chart, width, height); ImageTable itbl = new ImageTable(db); ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); int imgId = itbl.addImg(vuser.getCn(), bis, "image/png"); return imgId; }
From source file:name.wramner.jmstools.analyzer.DataProvider.java
/** * Get a base64-encoded image for inclusion in an img tag with a chart with message flight times. * * @return chart as base64 string.//w w w.j ava 2s .c om */ public String getBase64EncodedFlightTimeMetricsImage() { TimeSeries timeSeries50p = new TimeSeries("Median"); TimeSeries timeSeries95p = new TimeSeries("95 percentile"); TimeSeries timeSeriesMax = new TimeSeries("Max"); for (FlightTimeMetrics m : getFlightTimeMetrics()) { Minute minute = new Minute(m.getPeriod()); timeSeries50p.add(minute, m.getMedian()); timeSeries95p.add(minute, m.getPercentile95()); timeSeriesMax.add(minute, m.getMax()); } TimeSeriesCollection timeSeriesCollection = new TimeSeriesCollection(timeSeries50p); timeSeriesCollection.addSeries(timeSeries95p); timeSeriesCollection.addSeries(timeSeriesMax); ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { JFreeChart chart = ChartFactory.createTimeSeriesChart("Flight time", "Time", "ms", timeSeriesCollection); chart.getPlot().setBackgroundPaint(Color.WHITE); ChartUtilities.writeChartAsPNG(bos, chart, 1024, 500); } catch (IOException e) { throw new UncheckedIOException(e); } return "data:image/png;base64," + Base64.getEncoder().encodeToString(bos.toByteArray()); }
From source file:com.algodefu.yeti.data.Pass.java
private void calculateEquityChartImg() throws IOException { int i = 0;//from w w w .ja v a2 s .c o m double sum = 0; TimeSeries equity = new TimeSeries("Equity"); // save values in temp array first, then use System.arraycopy to copy non empty values to this.equityArray double[][] tempEquityArr = new double[this.getTrades().length][4]; for (Trade trade : this.getTrades()) { if (trade.getCloseDateTime() != null) { sum += trade.getProfit(); equity.add(new Millisecond(Date.from(trade.getCloseDateTime().toInstant(ZoneOffset.UTC))), sum); tempEquityArr[i][0] = (double) trade.getCloseDateTime().toInstant(ZoneOffset.UTC).toEpochMilli(); tempEquityArr[i][1] = sum; tempEquityArr[i][2] = trade.getTradeID(); tempEquityArr[i][3] = trade.getProfit(); i++; } } this.equityArray = new double[i][4]; System.arraycopy(tempEquityArr, 0, this.equityArray, 0, i); TimeSeriesCollection dataset = new TimeSeriesCollection(equity); JFreeChart chart = ChartFactory.createTimeSeriesChart("", "", "", dataset, false, false, false); chart.getXYPlot().getDomainAxis().setTickLabelsVisible(false); chart.setBorderVisible(true); chart.getXYPlot().setRangeAxisLocation(AxisLocation.TOP_OR_RIGHT); chart.getXYPlot().getRenderer().setSeriesPaint(0, Color.blue); chart.getXYPlot().setBackgroundPaint(Color.white); chart.getXYPlot().setRangeGridlinePaint(Color.gray); chart.getXYPlot().setDomainGridlinePaint(Color.gray); try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { ChartUtilities.writeChartAsPNG(baos, chart, 320, 180); baos.flush(); this.equityChartByteArray = baos.toByteArray(); } catch (IOException e) { throw e; } }
From source file:PointingMap.java
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { Connection conn = null;//ww w .ja v a 2 s . com Statement stmt = null; ResultSet rs = null; ResultSetMetaData rsm = null; OutputStream out = response.getOutputStream(); try { String dbHost = request.getParameter("dbHost"); String dbName = request.getParameter("dbName"); conn = connect(dbHost, dbName); // get & plot target catalog String targetCatQuery = "select " + "ra2000Hours, dec2000Deg " + "from TargetCat limit 200"; stmt = conn.createStatement(); rs = stmt.executeQuery(targetCatQuery); rsm = rs.getMetaData(); //int colCount = rsm.getColumnCount(); XYSeries series = new XYSeries("Target Catalog"); int raColIndex = 1; int decColIndex = 2; while (rs.next()) { series.add(rs.getDouble(raColIndex), rs.getDouble(decColIndex)); } XYDataset data = new XYSeriesCollection(series); stmt.close(); // Get latest primary beam pointing position String latestPointingQuery = "select " + "actId, ts, " + "raHours, decDeg " + "from TscopePointReq " + "where atabeam = 'primary' " + "order by actId desc limit 1"; stmt = conn.createStatement(); rs = stmt.executeQuery(latestPointingQuery); rsm = rs.getMetaData(); //int colCount = rsm.getColumnCount(); int actId = -1; String timeString = ""; double pointingRaHours = -1; double pointingDecDeg = -1; int actIdIndex = 1; int timeIndex = 2; raColIndex = 3; decColIndex = 4; while (rs.next()) { actId = rs.getInt(actIdIndex); timeString = rs.getString(timeIndex); pointingRaHours = rs.getDouble(raColIndex); pointingDecDeg = rs.getDouble(decColIndex); } String plotTitle = "ATA Primary Pointing" + " (Act Id: " + actId + ")" + " " + timeString; JFreeChart chart = ChartFactory.createScatterPlot(plotTitle, "RA (Hours)", // x-axis label "Dec (Deg)", // y axis label data, PlotOrientation.VERTICAL, false, // legend true, // tooltips false // urls ); // plot RA hours with higher values to the left //chart.getXYPlot().getDomainAxis().setInverted(true); chart.getXYPlot().getDomainAxis().setLowerBound(-1); chart.getXYPlot().getDomainAxis().setUpperBound(25); // increase axis label fonts for better readability Font axisFont = new Font("Serif", Font.BOLD, 14); chart.getXYPlot().getDomainAxis().setLabelFont(axisFont); chart.getXYPlot().getDomainAxis().setTickLabelFont(axisFont); chart.getXYPlot().getRangeAxis().setLabelFont(axisFont); chart.getXYPlot().getRangeAxis().setTickLabelFont(axisFont); // show current pointing as crosshairs chart.getXYPlot().setDomainCrosshairValue(pointingRaHours); chart.getXYPlot().setRangeCrosshairValue(pointingDecDeg); chart.getXYPlot().setDomainCrosshairVisible(true); chart.getXYPlot().setRangeCrosshairVisible(true); chart.getXYPlot().setDomainCrosshairPaint(Color.BLACK); chart.getXYPlot().setRangeCrosshairPaint(Color.BLACK); Stroke stroke = new BasicStroke(2); chart.getXYPlot().setDomainCrosshairStroke(stroke); chart.getXYPlot().setRangeCrosshairStroke(stroke); // set hat creek dec range chart.getXYPlot().getRangeAxis().setLowerBound(-40); chart.getXYPlot().getRangeAxis().setUpperBound(90); XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) chart.getXYPlot().getRenderer(); int seriesIndex = 0; renderer.setSeriesPaint(seriesIndex, Color.BLUE); Shape circularShape = new Ellipse2D.Double(-1.0, -1.0, 1.2, 1.2); renderer.setSeriesShape(seriesIndex, circularShape); // Default shape [0-9]: 0=square 1=circle 2=uptriangle 3=diamond... //renderer.setShape(DefaultDrawingSupplier.DEFAULT_SHAPE_SEQUENCE[1]); response.setContentType("image/png"); int width = 800; int height = 600; ChartUtilities.writeChartAsPNG(out, chart, width, height); } catch (Exception e) { throw new ServletException(e); } finally { try { if (stmt != null) { stmt.close(); } if (conn != null) { conn.close(); } } catch (SQLException sql) { } } }
From source file:edu.fullerton.viewerplugin.PluginSupport.java
public void saveImageAsPNGFile(ChartPanel cp, String fname) throws WebUtilException { FileOutputStream fos = null;/*w w w. j av a2 s. com*/ try { JFreeChart chart = cp.getChart(); fos = new FileOutputStream(fname); ChartUtilities.writeChartAsPNG(fos, chart, width, height); fos.close(); fos = null; } catch (Exception ex) { throw new WebUtilException("Saving image: " + ex.getClass() + " - " + ex.getLocalizedMessage()); } finally { try { if (fos != null) { fos.close(); } } catch (Exception ex) { throw new WebUtilException("Saving image: " + ex.getClass() + " - " + ex.getLocalizedMessage()); } } }
From source file:it.eng.spagobi.services.execute.service.ServiceChartImpl.java
public byte[] executeChart(String token, String userId, String label, HashMap parameters) { logger.debug("IN"); Monitor monitor = MonitorFactory.start("spagobi.service.execute.executeChart"); logger.debug("Getting profile"); byte[] returnImage = null; IEngUserProfile userProfile = null;//from www. jav a2 s . c o m try { userProfile = it.eng.spagobi.commons.utilities.GeneralUtilities.createNewUserProfile(userId); } catch (Exception e2) { logger.error("Error recovering profile", e2); return "".getBytes(); } logger.debug("Getting the chart object"); IBIObjectDAO dao; BIObject obj = null; try { dao = DAOFactory.getBIObjectDAO(); if (label != null) obj = dao.loadBIObjectByLabel(label); } catch (EMFUserError e) { logger.error("Error in recovering object", e); return "".getBytes(); } //***************************** GET THE TEMPLATE****************************************** if (obj != null) { logger.debug("Getting template"); SourceBean content = null; byte[] contentBytes = null; try { ObjTemplate template = DAOFactory.getObjTemplateDAO().getBIObjectActiveTemplate(obj.getId()); if (template == null) throw new Exception("Active Template null"); contentBytes = template.getContent(); if (contentBytes == null) throw new Exception("Content of the Active template null"); // get bytes of template and transform them into a SourceBean String contentStr = new String(contentBytes); content = SourceBean.fromXMLString(contentStr); } catch (Exception e) { logger.error("Error in reading template", e); return "".getBytes(); } String type = content.getName(); String subtype = (String) content.getAttribute("type"); String data = ""; try { if (obj.getDataSetId() != null) { data = obj.getDataSetId().toString(); } else { throw new Exception("Data Set not defined"); } } catch (Exception e) { logger.error("Error in reading dataset", e); return "".getBytes(); } //***************************** GET PARAMETERS****************************************** logger.debug("Getting parameters"); HashMap parametersMap = null; //Search if the chart has parameters List parametersList = null; try { parametersList = DAOFactory.getBIObjectDAO().getBIObjectParameters(obj); } catch (EMFUserError e1) { logger.error("Error in retrieving parameters", e1); return "".getBytes(); } parametersMap = new HashMap(); if (parametersList != null && !parametersList.isEmpty()) { for (Iterator iterator = parametersList.iterator(); iterator.hasNext();) { BIObjectParameter par = (BIObjectParameter) iterator.next(); String url = par.getParameterUrlName(); String value = (String) parameters.get(url); //List values=par.getParameterValues(); if (value != null) { parametersMap.put(url, value); } } } // if there are other parameters (like targets or baseline) that do not belong to the BiObject pass those anyway, extend this behaviour if necessary for (Iterator iterator = parameters.keySet().iterator(); iterator.hasNext();) { String namePar = (String) iterator.next(); if (namePar.startsWith("target") || namePar.startsWith("baseline")) { Object value = parameters.get(namePar); parametersMap.put(namePar, value); } } logger.debug("Creating the chart"); ChartImpl sbi = null; // set the right chart type sbi = ChartImpl.createChart(type, subtype); sbi.setProfile(userProfile); sbi.setType(type); sbi.setSubtype(subtype); sbi.setData(data); sbi.setParametersObject(parametersMap); // configure the chart with template parameters sbi.configureChart(content); DatasetMap datasets = null; try { datasets = sbi.calculateValue(); } catch (Exception e) { logger.error("Error in reading the value, check the dataset", e); return "".getBytes(); } JFreeChart chart = null; // create the chart chart = sbi.createChart(datasets); ByteArrayOutputStream out = null; try { logger.debug("Write PNG Image"); out = new ByteArrayOutputStream(); ChartUtilities.writeChartAsPNG(out, chart, sbi.getWidth(), sbi.getHeight()); returnImage = out.toByteArray(); } catch (Exception e) { logger.error("Error while creating the image", e); return "".getBytes(); } finally { try { out.close(); } catch (IOException e) { logger.error("Error while closing stream", e); } monitor.stop(); } //out.flush(); } return returnImage; }