Java Code Examples for org.jfree.chart.ChartUtils#writeChartAsPNG()

The following examples show how to use org.jfree.chart.ChartUtils#writeChartAsPNG() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: UnitStatusPage.java    From freeacs with MIT License 6 votes vote down vote up
/**
 * Gets the report chart image bytes.
 *
 * @param chartMaker the chart maker
 * @param chart the chart
 * @param width the width
 * @param height the height
 * @return the report chart image bytes
 * @throws Exception the exception
 */
public static byte[] getReportChartImageBytes(
    Chart<?> chartMaker, JFreeChart chart, int width, int height) throws Exception {
  if (chart == null && chartMaker != null) {
    chart = chartMaker.makeTimeChart(null, null, null, null);
  } else if (chart == null) {
    throw new IllegalArgumentException("Chart<?> and JFreeChart is NULL.");
  }
  if (chart.getPlot() instanceof XYPlot) {
    XYPlot plot = (XYPlot) chart.getPlot();
    XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRenderer();
    renderer.setDefaultShapesVisible(true);
    renderer.setDrawOutlines(true);
    renderer.setUseFillPaint(true);
    renderer.setDefaultFillPaint(Color.white);
  }
  ByteArrayOutputStream image = new ByteArrayOutputStream();
  ChartUtils.writeChartAsPNG(image, chart, width, height);
  return image.toByteArray();
}
 
Example 2
Source File: UserChartController.java    From airsonic-advanced with GNU General Public License v3.0 5 votes vote down vote up
@GetMapping
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    String type = request.getParameter("type");
    CategoryDataset dataset = createDataset(type);
    JFreeChart chart = createChart(dataset, request);

    int imageHeight = Math.max(IMAGE_MIN_HEIGHT, 15 * dataset.getColumnCount());

    ChartUtils.writeChartAsPNG(response.getOutputStream(), chart, IMAGE_WIDTH, imageHeight);
    return null;
}
 
Example 3
Source File: UserChartController.java    From airsonic with GNU General Public License v3.0 5 votes vote down vote up
@GetMapping
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    String type = request.getParameter("type");
    CategoryDataset dataset = createDataset(type);
    JFreeChart chart = createChart(dataset, request);

    int imageHeight = Math.max(IMAGE_MIN_HEIGHT, 15 * dataset.getColumnCount());

    ChartUtils.writeChartAsPNG(response.getOutputStream(), chart, IMAGE_WIDTH, imageHeight);
    return null;
}
 
Example 4
Source File: ChartResult.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Executes the result. Writes the given chart as a PNG 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.
 */
@Override
public void execute( ActionInvocation invocation )
    throws Exception
{
    JFreeChart stackChart = (JFreeChart) invocation.getStack().findValue( "chart" );

    chart = stackChart != null ? stackChart : chart;

    Integer stackHeight = (Integer) invocation.getStack().findValue( "height" );

    height = stackHeight != null && stackHeight > 0 ? stackHeight : height != null ? height : DEFAULT_HEIGHT;

    Integer stackWidth = (Integer) invocation.getStack().findValue( "width" );

    width = stackWidth != null && stackWidth > 0 ? stackWidth : width != null ? width : DEFAULT_WIDTH;

    String stackFilename = (String) invocation.getStack().findValue( "filename" );

    filename = StringUtils.defaultIfEmpty( stackFilename, DEFAULT_FILENAME );

    if ( chart == null )
    {
        log.warn( "No chart found" );
        return;
    }

    HttpServletResponse response = ServletActionContext.getResponse();
    ContextUtils.configureResponse( response, ContextUtils.CONTENT_TYPE_PNG, true, filename, false );

    OutputStream os = response.getOutputStream();
    ChartUtils.writeChartAsPNG( os, chart, width, height );
    os.flush();
}
 
Example 5
Source File: ChartController.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@RequestMapping( value = { "/{uid}/data", "/{uid}/data.png" }, method = RequestMethod.GET )
public void getChart(
    @PathVariable( "uid" ) String uid,
    @RequestParam( value = "date", required = false ) Date date,
    @RequestParam( value = "ou", required = false ) String ou,
    @RequestParam( value = "width", defaultValue = "800", required = false ) int width,
    @RequestParam( value = "height", defaultValue = "500", required = false ) int height,
    @RequestParam( value = "attachment", required = false ) boolean attachment,
    HttpServletResponse response ) throws IOException, WebMessageException
{
    final Visualization visualization = visualizationService.getVisualizationNoAcl( uid );
    final Chart chart = convertToChart( visualization );

    if ( chart == null )
    {
        throw new WebMessageException( WebMessageUtils.notFound( "Chart does not exist: " + uid ) );
    }

    OrganisationUnit unit = ou != null ? organisationUnitService.getOrganisationUnit( ou ) : null;

    JFreeChart jFreeChart = chartService.getJFreeChart( chart, date, unit, i18nManager.getI18nFormat() );

    String filename = CodecUtils.filenameEncode( chart.getName() ) + ".png";

    contextUtils.configureResponse( response, ContextUtils.CONTENT_TYPE_PNG, CacheStrategy.RESPECT_SYSTEM_SETTING, filename, attachment );

    ChartUtils.writeChartAsPNG( response.getOutputStream(), jFreeChart, width, height );
}
 
Example 6
Source File: ChartController.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@RequestMapping( value = { "/data", "/data.png" }, method = RequestMethod.GET )
public void getChart(
    @RequestParam( value = "in" ) String indicatorUid,
    @RequestParam( value = "ou" ) String organisationUnitUid,
    @RequestParam( value = "periods", required = false ) boolean periods,
    @RequestParam( value = "width", defaultValue = "800", required = false ) int width,
    @RequestParam( value = "height", defaultValue = "500", required = false ) int height,
    @RequestParam( value = "skipTitle", required = false ) boolean skipTitle,
    @RequestParam( value = "attachment", required = false ) boolean attachment,
    HttpServletResponse response ) throws IOException
{
    Indicator indicator = indicatorService.getIndicator( indicatorUid );
    OrganisationUnit unit = organisationUnitService.getOrganisationUnit( organisationUnitUid );

    JFreeChart chart;

    if ( periods )
    {
        chart = chartService.getJFreePeriodChart( indicator, unit, !skipTitle, i18nManager.getI18nFormat() );
    }
    else
    {
        chart = chartService.getJFreeOrganisationUnitChart( indicator, unit, !skipTitle, i18nManager.getI18nFormat() );
    }

    contextUtils.configureResponse( response, ContextUtils.CONTENT_TYPE_PNG, CacheStrategy.RESPECT_SYSTEM_SETTING, "chart.png", attachment );

    ChartUtils.writeChartAsPNG( response.getOutputStream(), chart, width, height );
}
 
Example 7
Source File: EventChartController.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@RequestMapping( value = { "/{uid}/data", "/{uid}/data.png" }, method = RequestMethod.GET )
public void getChart(
    @PathVariable( "uid" ) String uid,
    @RequestParam( value = "date", required = false ) Date date,
    @RequestParam( value = "ou", required = false ) String ou,
    @RequestParam( value = "width", defaultValue = "800", required = false ) int width,
    @RequestParam( value = "height", defaultValue = "500", required = false ) int height,
    @RequestParam( value = "attachment", required = false ) boolean attachment,
    HttpServletResponse response ) throws IOException, WebMessageException
{
    EventChart chart = eventChartService.getEventChart( uid ); // TODO no acl?

    if ( chart == null )
    {
        throw new WebMessageException( WebMessageUtils.notFound( "Event chart does not exist: " + uid ) );
    }

    OrganisationUnit unit = ou != null ? organisationUnitService.getOrganisationUnit( ou ) : null;

    JFreeChart jFreeChart = chartService.getJFreeChart( chart, date, unit, i18nManager.getI18nFormat() );

    String filename = CodecUtils.filenameEncode( chart.getName() ) + ".png";

    contextUtils.configureResponse( response, ContextUtils.CONTENT_TYPE_PNG, CacheStrategy.RESPECT_SYSTEM_SETTING, filename, attachment );

    ChartUtils.writeChartAsPNG( response.getOutputStream(), jFreeChart, width, height );
}
 
Example 8
Source File: ChartImageResource.java    From webanno with Apache License 2.0 5 votes vote down vote up
@Override
protected byte[] getImageData(Attributes aAttributes)
{
    try {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ChartUtils.writeChartAsPNG(bos, chart, width, height);
        return bos.toByteArray();
    }
    catch (IOException e) {
        return new byte[0];
    }
}
 
Example 9
Source File: ReportPage.java    From freeacs with MIT License 4 votes vote down vote up
private void displayReportChartWithImageMap(
    Map<String, Object> root,
    int numberOfColumns,
    int averageLengthPrLegend,
    List<String> aggregation,
    HttpSession session) {
  StringWriter stringWriter = new StringWriter();
  PrintWriter writer = new PrintWriter(stringWriter);

  boolean shouldZoom = true;

  switch (reportType) {
    case JOB:
    case UNIT:
      shouldZoom = false;
      break;
    default:
      break;
  }

  String clickablePointUrl = "";
  if (shouldZoom || periodType.getSelected().isLongerThan(PeriodType.HOUR)) {
    clickablePointUrl =
        generateClickablePointUrl(
            periodType.getSelected(),
            reportType.getName(),
            method.getSelected(),
            optionalmethod.getSelected());
  }

  XYPlot plot = (XYPlot) chart.getPlot();
  XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRenderer();
  XYURLGenerator urls = new ReportURLGenerator(clickablePointUrl, chart, aggregation);
  renderer.setURLGenerator(urls);
  XYSeriesLabelGenerator slg =
      new CustomXYSeriesLabelGenerator("javascript:xAPS.report.updateReport(%d);");
  renderer.setLegendItemURLGenerator(slg);
  renderer.setDefaultShapesVisible(true);
  renderer.setDrawOutlines(true);
  renderer.setUseFillPaint(true);
  renderer.setDefaultFillPaint(Color.white);

  try {
    ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
    ByteArrayOutputStream image = new ByteArrayOutputStream();

    int chartWidth = 700 + 10 * averageLengthPrLegend * numberOfColumns + 35 * numberOfColumns;

    ChartUtils.writeChartAsPNG(image, chart, chartWidth, 400, info);

    session.setAttribute("JFreeChartPNG" + reportType.getName(), image.toByteArray());

    ImageMapUtils.writeImageMap(
        writer,
        "chart" + reportType.getName(),
        info,
        arg0 -> " title=\"" + arg0 + "\" alt=\"" + arg0 + "\"",
        arg0 -> " href=\"" + arg0 + "\"");

    writer.println(
        "<img src=\""
            + Page.REPORT.getUrl()
            + "&type="
            + reportType.getName()
            + "&image=true&d="
            + new Date().getTime()
            + "\" border=\"0\" usemap=\"#chart"
            + reportType.getName()
            + "\" id=\"ImageMapImg\" alt=\"ReportImage\"/>");
    writer.close();

    root.put("imagemap", stringWriter.toString());
  } catch (IOException e) {
    e.printStackTrace();
  }
}
 
Example 10
Source File: ChartController.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@RequestMapping( value = { "/history/data", "/history/data.png" }, method = RequestMethod.GET )
public void getHistoryChart(
    @RequestParam String de,
    @RequestParam String co,
    @RequestParam String cp,
    @RequestParam String pe,
    @RequestParam String ou,
    @RequestParam( defaultValue = "525", required = false ) int width,
    @RequestParam( defaultValue = "300", required = false ) int height,
    HttpServletResponse response ) throws IOException, WebMessageException
{
    DataElement dataElement = dataElementService.getDataElement( de );

    if ( dataElement == null )
    {
        throw new WebMessageException( WebMessageUtils.conflict( "Data element does not exist: " + de ) );
    }

    CategoryOptionCombo categoryOptionCombo = categoryService.getCategoryOptionCombo( co );

    if ( categoryOptionCombo == null )
    {
        throw new WebMessageException( WebMessageUtils.conflict( "Category option combo does not exist: " + co ) );
    }

    CategoryOptionCombo attributeOptionCombo = categoryService.getCategoryOptionCombo( cp );

    if ( attributeOptionCombo == null )
    {
        throw new WebMessageException( WebMessageUtils.conflict( "Category option combo does not exist: " + cp ) );
    }

    Period period = PeriodType.getPeriodFromIsoString( pe );

    if ( period == null )
    {
        throw new WebMessageException( WebMessageUtils.conflict( "Period does not exist: " + pe ) );
    }

    OrganisationUnit organisationUnit = organisationUnitService.getOrganisationUnit( ou );

    if ( organisationUnit == null )
    {
        throw new WebMessageException( WebMessageUtils.conflict( "Organisation unit does not exist: " + ou ) );
    }

    contextUtils.configureResponse( response, ContextUtils.CONTENT_TYPE_PNG, CacheStrategy.RESPECT_SYSTEM_SETTING, "chart.png", false );

    JFreeChart chart = chartService.getJFreeChartHistory( dataElement, categoryOptionCombo, attributeOptionCombo, period, organisationUnit, 13, i18nManager.getI18nFormat() );

    ChartUtils.writeChartAsPNG( response.getOutputStream(), chart, width, height );
}
 
Example 11
Source File: ScatterPlot.java    From Benchmark with GNU General Public License v2.0 4 votes vote down vote up
public void writeChartToFile(File f, int height) throws IOException {
    FileOutputStream stream = new FileOutputStream(f);
    ChartUtils.writeChartAsPNG(stream, chart, (int)Math.round(height*1.4), height);
    stream.close();
}