Java源码示例:org.jfree.chart.ChartUtils

示例1
/**
 * Opens a file chooser and gives the user an opportunity to save the chart in PNG format.
 *
 * @throws IOException if there is an I/O error.
 */
@Override
public void doSaveAs() throws IOException {
  JFileChooser fileChooser = new JFileChooser();
  fileChooser.setCurrentDirectory(this.getDefaultDirectoryForSaveAs());
  FileNameExtensionFilter filter =
      new FileNameExtensionFilter(localizationResources.getString("PNG_Image_Files"), "png");
  fileChooser.addChoosableFileFilter(filter);
  fileChooser.setFileFilter(filter);

  int option = fileChooser.showSaveDialog(this);
  if (option == JFileChooser.APPROVE_OPTION) {
    String filename = fileChooser.getSelectedFile().getPath();
    if (isEnforceFileExtensions()) {
      if (!filename.endsWith(".png")) {
        filename = filename + ".png";
      }
    }
    ChartUtils.saveChartAsPNG(new File(filename), getChart(), getWidth(), getHeight(),
        getChartRenderingInfo());
  }
}
 
示例2
/**
 * 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();
}
 
示例3
/**
 * Opens a file chooser and gives the user an opportunity to save the chart in PNG format.
 *
 * @throws IOException if there is an I/O error.
 */
@Override
public void doSaveAs() throws IOException {
  JFileChooser fileChooser = new JFileChooser();
  fileChooser.setCurrentDirectory(this.getDefaultDirectoryForSaveAs());
  FileNameExtensionFilter filter =
      new FileNameExtensionFilter(localizationResources.getString("PNG_Image_Files"), "png");
  fileChooser.addChoosableFileFilter(filter);
  fileChooser.setFileFilter(filter);

  int option = fileChooser.showSaveDialog(this);
  if (option == JFileChooser.APPROVE_OPTION) {
    String filename = fileChooser.getSelectedFile().getPath();
    if (isEnforceFileExtensions()) {
      if (!filename.endsWith(".png")) {
        filename = filename + ".png";
      }
    }
    ChartUtils.saveChartAsPNG(new File(filename), getChart(), getWidth(), getHeight(),
        getChartRenderingInfo());
  }
}
 
示例4
/**
 * Opens a file chooser and gives the user an opportunity to save the chart in PNG format.
 *
 * @throws IOException if there is an I/O error.
 */
@Override
public void doSaveAs() throws IOException {
  JFileChooser fileChooser = new JFileChooser();
  fileChooser.setCurrentDirectory(this.getDefaultDirectoryForSaveAs());
  FileNameExtensionFilter filter =
      new FileNameExtensionFilter(localizationResources.getString("PNG_Image_Files"), "png");
  fileChooser.addChoosableFileFilter(filter);
  fileChooser.setFileFilter(filter);

  int option = fileChooser.showSaveDialog(this);
  if (option == JFileChooser.APPROVE_OPTION) {
    String filename = fileChooser.getSelectedFile().getPath();
    if (isEnforceFileExtensions()) {
      if (!filename.endsWith(".png")) {
        filename = filename + ".png";
      }
    }
    ChartUtils.saveChartAsPNG(new File(filename), getChart(), getWidth(), getHeight(),
        getChartRenderingInfo());
  }
}
 
示例5
@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;
}
 
示例6
public static void writeChartToPNG(JFreeChart chart, ChartRenderingInfo info, int width,
    int height, File fileName, int resolution) throws IOException {
  if (resolution == 72)
    writeChartToPNG(chart, info, width, height, fileName);
  else {
    OutputStream out = new BufferedOutputStream(new FileOutputStream(fileName));
    try {
      BufferedImage image = paintScaledChartToBufferedImage(chart, info, out, width, height,
          resolution, BufferedImage.TYPE_INT_ARGB);
      out.write(ChartUtils.encodeAsPNG(image));
    } finally {
      out.close();
    }
  }
}
 
示例7
@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;
}
 
示例8
/**
 * Draw a JFreeChart to an image based on values from a MultiTable.
 * @param table MultiTable to retrieve values from
 * @param config chart configuration options
 */
public static void drawChartAsFile(MultiTable table, MultiTableChartConfig config) {
  
  JFreeChart chart = createChart(table, config);
  
  // Save the chart as a PNG image to the file system
  try {
    ChartUtils.saveChartAsPNG(new File(config.getFilename()), chart, config.getWidth(),
        config.getHeight());
  } catch (IOException e) {
    e.printStackTrace();
  }
}
 
示例9
/**
 * Draw a JFreeChart to an image based on values from a MultiTable.
 * @param person Person to retrieve attributes from
 * @param config chart configuration options
 */
public static void drawChartAsFile(Person person, PersonChartConfig config) {
  
  JFreeChart chart = createChart(person, config);
  
  // Save the chart as a PNG image to the file system
  try {
    ChartUtils.saveChartAsPNG(new File(config.getFilename()), chart, config.getWidth(),
        config.getHeight());
  } catch (IOException e) {
    e.printStackTrace();
  }
}
 
示例10
/**
 * Draw a JFreeChart to a base64 encoded image based on values from a MultiTable.
 * @param table MultiTable to retrieve values from
 * @param config chart configuration options
 */
public static String drawChartAsBase64(MultiTable table, MultiTableChartConfig config)
    throws IOException {
  
  JFreeChart chart = createChart(table, config);

  byte[] imgBytes = ChartUtils.encodeAsPNG(chart.createBufferedImage(config.getWidth(),
      config.getHeight()));
  return new String(Base64.getEncoder().encode(imgBytes));
}
 
示例11
/**
 * Draw a JFreeChart to a base64 encoded image based on values from a MultiTable.
 * @param person Person to retrieve attribute values from
 * @param config chart configuration options
 */
public static String drawChartAsBase64(Person person, PersonChartConfig config)
    throws IOException {
  
  JFreeChart chart = createChart(person, config);

  byte[] imgBytes = ChartUtils.encodeAsPNG(chart.createBufferedImage(config.getWidth(),
      config.getHeight()));
  return new String(Base64.getEncoder().encode(imgBytes));
}
 
示例12
/**
 * 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();
}
 
示例13
@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 );
}
 
示例14
@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 );
}
 
示例15
@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 );
}
 
示例16
public static void writeChartToPNG(JFreeChart chart, ChartRenderingInfo info, int width,
    int height, File fileName, int resolution) throws IOException {
  if (resolution == 72)
    writeChartToPNG(chart, info, width, height, fileName);
  else {
    OutputStream out = new BufferedOutputStream(new FileOutputStream(fileName));
    try {
      BufferedImage image = paintScaledChartToBufferedImage(chart, info, out, width, height,
          resolution, BufferedImage.TYPE_INT_ARGB);
      out.write(ChartUtils.encodeAsPNG(image));
    } finally {
      out.close();
    }
  }
}
 
示例17
public static void writeChartToPNG(JFreeChart chart, ChartRenderingInfo info, int width,
    int height, File fileName, int resolution) throws IOException {
  if (resolution == 72)
    writeChartToPNG(chart, info, width, height, fileName);
  else {
    OutputStream out = new BufferedOutputStream(new FileOutputStream(fileName));
    try {
      BufferedImage image = paintScaledChartToBufferedImage(chart, info, out, width, height,
          resolution, BufferedImage.TYPE_INT_ARGB);
      out.write(ChartUtils.encodeAsPNG(image));
    } finally {
      out.close();
    }
  }
}
 
示例18
@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];
    }
}
 
示例19
public static void writeChartToPNG(JFreeChart chart, ChartRenderingInfo info, int width,
    int height, File fileName) throws IOException {
  ChartUtils.saveChartAsPNG(fileName, chart, width, height, info);
}
 
示例20
public static void writeChartToJPEG(JFreeChart chart, int width, int height, File fileName)
    throws IOException {
  ChartUtils.saveChartAsJPEG(fileName, chart, width, height);
}
 
示例21
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();
  }
}
 
示例22
@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 );
}
 
示例23
public static void writeChartToPNG(JFreeChart chart, ChartRenderingInfo info, int width,
    int height, File fileName) throws IOException {
  ChartUtils.saveChartAsPNG(fileName, chart, width, height, info);
}
 
示例24
public static void writeChartToJPEG(JFreeChart chart, int width, int height, File fileName)
    throws IOException {
  ChartUtils.saveChartAsJPEG(fileName, chart, width, height);
}
 
示例25
public static void writeChartToPNG(JFreeChart chart, ChartRenderingInfo info, int width,
    int height, File fileName) throws IOException {
  ChartUtils.saveChartAsPNG(fileName, chart, width, height, info);
}
 
示例26
public static void writeChartToJPEG(JFreeChart chart, int width, int height, File fileName)
    throws IOException {
  ChartUtils.saveChartAsJPEG(fileName, chart, width, height);
}
 
示例27
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();
}