// --- GET GROWTH GRAPHS -----------------------------------------------------------------------
  protected PdfPTable getGrowthGraphs() throws Exception {
    PdfPTable growthTable = new PdfPTable(1);
    growthTable.setWidthPercentage(pageWidth);

    // *** height graph ****************************************************
    ByteArrayOutputStream osHeight = new ByteArrayOutputStream();
    ChartUtilities.writeChartAsPNG(osHeight, getHeightGraph(), 680, 350);

    // put image in cell
    cell = new PdfPCell();
    cell.setImage(com.itextpdf.text.Image.getInstance(osHeight.toByteArray()));
    cell.setBorder(PdfPCell.NO_BORDER);
    cell.setPaddingRight(10);
    growthTable.addCell(cell);

    // spacer
    growthTable.addCell(createBorderlessCell("", 30, 1));

    // *** weight graph ****************************************************
    ByteArrayOutputStream osWeight = new ByteArrayOutputStream();
    ChartUtilities.writeChartAsPNG(osWeight, getWeightGraph(), 680, 350);

    // put image in cell
    cell = new PdfPCell();
    cell.setImage(com.itextpdf.text.Image.getInstance(osWeight.toByteArray()));
    cell.setBorder(PdfPCell.NO_BORDER);
    cell.setPaddingRight(10);
    growthTable.addCell(cell);

    return growthTable;
  }
  /*
   * Metodo que aplica o filtro
   */
  public static void Apply(BufferedImage image, String savePath) {
    // Chamada do metodo que gera os dados do histograma
    GetData(image);

    // Dataset que gera o grafico
    DefaultCategoryDataset ds = new DefaultCategoryDataset();

    // Loop que percorre o array de dados do histograma
    for (int k = 0; k < data.length; k++) {
      // Adiciona o valor ao dataset
      ds.setValue(data[k], "Imagem", Integer.toString(data[k]));
    }

    // Gera o grafico
    JFreeChart grafico =
        ChartFactory.createLineChart(
            "Histograma",
            "Tons de cinza",
            "Valor",
            ds,
            PlotOrientation.VERTICAL,
            true,
            true,
            false);

    // Salva o grafico em um arquivo de png
    try {
      OutputStream arquivo = new FileOutputStream(savePath);
      ChartUtilities.writeChartAsPNG(arquivo, grafico, 550, 400);
      arquivo.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
 public void saveAsFile(String outputPath) {
   FileOutputStream out = null;
   try {
     File outFile = new File(outputPath);
     if (!outFile.getParentFile().exists()) {
       outFile.getParentFile().mkdirs();
     }
     out = new FileOutputStream(outputPath);
     // 保存为PNG
     ChartUtilities.writeChartAsPNG(out, jfc, 800, 600);
     // 保存为JPEG
     // ChartUtilities.writeChartAsJPEG(out, chart, 500, 400);
     out.flush();
   } catch (FileNotFoundException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   } finally {
     if (out != null) {
       try {
         out.close();
       } catch (IOException e) {
         // do nothing
       }
     }
   }
 }
Example #4
0
  /**
   * @param response
   * @param type
   * @param alphaList
   * @param title
   * @param xTitle
   * @param yTitle
   */
  protected void createChart(
      final CollStatInfo csi,
      final Vector<Pair<String, Integer>> list,
      final String xTitle,
      final String yTitle) {
    DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    for (Pair<String, Integer> p : list) {
      dataset.addValue(p.second, p.first, "");
    }

    // if (StringUtils.isEmpty(csi.getInstName()))
    // {
    //    csi.setInstName(getProviderNameFromInstCode(csi.getProviderId()));
    // }

    JFreeChart chart =
        ChartFactory.createBarChart(
            csi.getTitle(), xTitle, yTitle, dataset, PlotOrientation.VERTICAL, true, true, false);

    // chart.getCategoryPlot().setRenderer(new CustomColorBarChartRenderer());

    chart.setBackgroundPaint(new Color(228, 243, 255));

    try {
      Integer hashCode = csi.hashCode();
      csi.setChartFileName(hashCode + ".png");
      DataOutputStream dos =
          new DataOutputStream(
              new FileOutputStream(new File("reports/charts/" + csi.getChartFileName())));
      ChartUtilities.writeChartAsPNG(dos, chart, 700, 600);

    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
Example #5
0
  public void png() throws IOException {

    this.response.setContentType("image/png");
    StandardChartTheme standardChartTheme = new StandardChartTheme(theme);
    setChartTheme(standardChartTheme);
    JFreeChart jFreeChart = createChart();
    preRender(jFreeChart);
    ChartUtilities.writeChartAsPNG(this.response.getOutputStream(), jFreeChart, width, height);
  }
 /**
  * Generates a byte array (a png image file) from a JFreeChart object
  *
  * @param chart A chart object from which the image is created
  * @param width Width of the created image
  * @param height Height of the created image
  * @return Byte array representing a png image file
  */
 protected byte[] getChartImageByteArray(JFreeChart chart, int width, int height) {
   try {
     ByteArrayOutputStream out = new ByteArrayOutputStream();
     ChartUtilities.writeChartAsPNG(out, chart, width, height);
     return out.toByteArray();
   } catch (IOException e) {
     e.printStackTrace();
   }
   return null;
 }
Example #7
0
  /**
   * Plots the chart and sends it in the form of ByteArrayOutputStream to outside.
   *
   * @return Returns the byteArrayOutputStream.
   */
  public synchronized ByteArrayOutputStream writePlot() {
    if (!changed) return byteArrayOutputStream;
    byteArrayOutputStream.reset();
    try {
      ChartUtilities.writeChartAsPNG(byteArrayOutputStream, chart, width, height, false, 8);

    } catch (IOException e) {
      logger.warn(e.getMessage(), e);
    }
    return byteArrayOutputStream;
  }
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws IOException {

    response.setContentType("image/png");

    OutputStream outputStream = response.getOutputStream();

    CategoryDataset dataset = createDataset();
    JFreeChart chart = getChart(dataset);
    int width = 400;
    int height = 250;
    ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
  }
  private PdfPCell createKPGSPieChartCell(KeyValue[] values, String title)
      throws IOException, BadElementException {
    DefaultPieDataset dataset = new DefaultPieDataset();
    for (int n = 0; n < values.length; n++) {
      dataset.setValue(values[n].getKey(), new Double(values[n].getValue()).doubleValue());
    }
    // create chart
    final JFreeChart chart =
        ChartFactory.createPieChart(
            title, // chart title
            dataset, // data
            true, // legend
            false, // tooltips
            false // urls
            );
    // customize chart
    PiePlot plot = (PiePlot) chart.getPlot();
    plot.setBackgroundPaint(java.awt.Color.WHITE);
    if (values.length > 0) {
      if (values[0].getKey().equalsIgnoreCase("?") && values.length > 1) {
        plot.setExplodePercent(values[1].getKey(), 0.2);
      } else {
        plot.setExplodePercent(values[0].getKey(), 0.2);
      }
    }
    plot.setLegendLabelGenerator(new KPGSLegendGenerator());
    plot.setLabelGenerator(new KPGSLabelGenerator(values));
    plot.setOutlineVisible(false);
    chart.setAntiAlias(true);
    LegendTitle legendTitle = (LegendTitle) chart.getSubtitle(0);
    legendTitle.setFrame(BlockBorder.NONE);
    legendTitle.setBackgroundPaint(null);

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    ChartUtilities.writeChartAsPNG(
        os,
        chart,
        MedwanQuery.getInstance().getConfigInt("stats.piechartwidth", 640),
        MedwanQuery.getInstance().getConfigInt("stats.piechartheight", 480));
    cell = new PdfPCell();
    cell.setColspan(50);
    cell.setImage(Image.getInstance(os.toByteArray()));
    cell.setBorder(PdfPCell.NO_BORDER);
    cell.setPaddingLeft(5);
    cell.setPaddingRight(5);
    return cell;
  }
 public javax.swing.ImageIcon plotagem(GeradorDeGraficosLinha ger) throws IOException {
   this.ds = ger.ds;
   this.titulox = ger.titulox;
   this.tituloy = ger.tituloy;
   this.titulografico = ger.titulografico;
   this.tituloplotagem = ger.tituloplotagem;
   this.tamanhografix = ger.tamanhografix;
   this.tamanhografiy = ger.tamanhografiy;
   this.grafi =
       new FileOutputStream(
           diretorioUsuario
               + File.separator
               + "InoveSystems"
               + File.separator
               + "Graficos"
               + File.separator
               + "grafico.png");
   JFreeChart grafico =
       ChartFactory.createLineChart(
           this.titulografico,
           this.titulox,
           this.tituloy,
           this.ds,
           PlotOrientation.VERTICAL,
           true,
           true,
           false);
   ChartUtilities.writeChartAsPNG(this.grafi, grafico, this.tamanhografix, this.tamanhografiy);
   this.grafi.close();
   return new javax.swing.ImageIcon(
       (diretorioUsuario
           + File.separator
           + "InoveSystems"
           + File.separator
           + "Graficos"
           + File.separator
           + "grafico.png"));
   //  graficolabel.setIcon(new javax.swing.ImageIcon((diretorioUsuario + File.separator +
   // "InoveSystems" + File.separator + "Graficos" + File.separator + "grafico.png")));
 }
  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");

    OutputStream out = response.getOutputStream();

    try {
      if (!CheckUserInSession.isUserInSession(request)) {
        logger.error("Unauthorized access!");
        response.sendRedirect("./login.jsp");
      } else {
        long flockId = Long.parseLong(request.getParameter("flockId"));
        FromDayToDay growDayRangeParam =
            new FromDayToDay(request.getParameter("fromDay"), request.getParameter("toDay"));
        try {
          FlockHistoryService flockHistoryService = new FlockHistoryServiceImpl();
          Map<Integer, String> historyByGrowDay =
              flockHistoryService.getFlockPerDayNotParsedReportsWithinRange(
                  flockId, growDayRangeParam);

          List<Map<Integer, Data>> dataHistoryList = new ArrayList<Map<Integer, Data>>();
          List<String> axisTitles = new ArrayList<String>();
          Locale currLocale = (Locale) request.getSession().getAttribute("currLocale");
          String lang = currLocale.toString().substring(0, 2);
          LanguageDao languageDao = DbImplDecider.use(DaoType.MYSQL).getDao(LanguageDao.class);
          long langId = languageDao.getLanguageId(lang);

          DataDao dataDao = DbImplDecider.use(DaoType.MYSQL).getDao(DataDao.class);
          Data data1 = dataDao.getById(PerGrowDayHistoryDataType.DAY_MORTALITY.getId());
          axisTitles.add(data1.getLabel());
          dataHistoryList.add(DataGraphCreator.createHistoryDataByGrowDay(historyByGrowDay, data1));

          Data data2 = dataDao.getById(PerGrowDayHistoryDataType.DAY_MORTALITY_MALE.getId());
          axisTitles.add(data2.getLabel());
          dataHistoryList.add(DataGraphCreator.createHistoryDataByGrowDay(historyByGrowDay, data2));

          Data data3 = dataDao.getById(PerGrowDayHistoryDataType.DAY_MORTALITY_FEMALE.getId());
          axisTitles.add(data3.getLabel());
          dataHistoryList.add(DataGraphCreator.createHistoryDataByGrowDay(historyByGrowDay, data3));

          HashMap<String, String> dictinary = createDictionary(currLocale);
          String title = dictinary.get("graph.mrt.title"); // "Daily Mortality";
          String xAxisTitle = dictinary.get("graph.mrt.axis.growday"); // "Grow Day[Day]";
          String yAxisTitle = dictinary.get("graph.mrt.axis.birds"); // "Birds";
          HistoryGraph mortalityGraph = new HistoryGraph();

          mortalityGraph.setDataHistoryList(dataHistoryList);
          mortalityGraph.createChart(title, xAxisTitle, yAxisTitle);
          request.setAttribute("fromDay", growDayRangeParam.getFromDay());
          request.setAttribute("toDay", growDayRangeParam.getToDay());
          ChartUtilities.writeChartAsPNG(out, mortalityGraph.getChart(), 800, 600);
          out.flush();
          out.close();
        } catch (Exception ex) {
          ex.printStackTrace();
          logger.error("Unknown error.", ex);
          EmptyGraph graph = new EmptyGraph();
          ChartUtilities.writeChartAsPNG(out, graph.getChart(), 600, 300);
          out.flush();
          out.close();
        }
      }
    } finally {
      out.close();
    }
  }
Example #12
0
  public static void writeChart(
      PointTimeSeriesCollection pointTimeSeriesCollection,
      boolean showLegend,
      OutputStream out,
      int width,
      int height,
      long from,
      long to)
      throws IOException {
    // 创建主题样式
    StandardChartTheme standardChartTheme = new StandardChartTheme("CN");
    // 设置标题字体
    standardChartTheme.setExtraLargeFont(new Font("隶书", Font.BOLD, 18));
    // 设置图例的字体
    standardChartTheme.setRegularFont(new Font("宋书", Font.PLAIN, 14));
    // 设置轴向的字体
    standardChartTheme.setLargeFont(new Font("宋书", Font.PLAIN, 14));
    // 应用主题样式
    ChartFactory.setChartTheme(standardChartTheme);

    JFreeChart chart =
        ChartFactory.createTimeSeriesChart(null, null, null, null, showLegend, false, false);
    chart.setBackgroundPaint(
        SystemSettingsDao.getColour(SystemSettingsDao.CHART_BACKGROUND_COLOUR));

    XYPlot plot = chart.getXYPlot();
    ((DateAxis) plot.getDomainAxis()).setTimeZone(pointTimeSeriesCollection.getTimeZone());
    plot.setBackgroundPaint(SystemSettingsDao.getColour(SystemSettingsDao.PLOT_BACKGROUND_COLOUR));
    Color gridlines = SystemSettingsDao.getColour(SystemSettingsDao.PLOT_GRIDLINE_COLOUR);
    plot.setDomainGridlinePaint(gridlines);
    plot.setRangeGridlinePaint(gridlines);
    ((NumberAxis) plot.getRangeAxis()).setAutoRangeStickyZero(false);

    double numericMin = 0;
    double numericMax = 1;

    int numericSeriesCount = pointTimeSeriesCollection.getNumericSeriesCount();
    if (pointTimeSeriesCollection.hasNumericData()) {
      for (int i = 0; i < numericSeriesCount; i++) {
        NumericTimeSeries nts = pointTimeSeriesCollection.getNumericTimeSeries(i);
        AbstractXYItemRenderer renderer;
        if (nts.getPlotType() == DataPointVO.PlotTypes.STEP) renderer = new XYStepRenderer();
        else if (nts.getPlotType() == DataPointVO.PlotTypes.LINE)
          renderer = new XYLineAndShapeRenderer(true, false);
        else {
          XYSplineRenderer spline = new XYSplineRenderer();
          spline.setBaseShapesVisible(false);
          renderer = spline;
        }

        if (nts.getPaint() != null) renderer.setSeriesPaint(0, nts.getPaint(), false);
        if (nts.getStroke() != null) renderer.setSeriesStroke(0, nts.getStroke(), false);

        plot.setDataset(i, new TimeSeriesCollection(nts.getTimeSeries()));
        plot.setRenderer(i, renderer);
      }

      numericMin = plot.getRangeAxis().getLowerBound();
      numericMax = plot.getRangeAxis().getUpperBound();

      if (!pointTimeSeriesCollection.hasMultiplePoints()) {
        // If this chart displays a single point, check if there should be a range description.
        TimeSeries timeSeries = pointTimeSeriesCollection.getNumericTimeSeries(0).getTimeSeries();
        String desc = timeSeries.getRangeDescription();
        if (!StringUtils.isBlank(desc)) {
          // Replace any HTML entities with Java equivalents
          desc = StripEntities.stripHTMLEntities(desc, ' ');
          plot.getRangeAxis().setLabel(desc);
        }
      }
    } else plot.getRangeAxis().setVisible(false);

    if (pointTimeSeriesCollection.getRangeMarkers() != null) {
      boolean rangeAdjusted = false;
      for (Marker marker : pointTimeSeriesCollection.getRangeMarkers()) {
        plot.addRangeMarker(marker);
        if (marker instanceof ValueMarker) {
          ValueMarker vm = (ValueMarker) marker;
          if (numericMin > vm.getValue()) {
            numericMin = vm.getValue();
            rangeAdjusted = true;
          }
          if (numericMax < vm.getValue()) {
            numericMax = vm.getValue();
            rangeAdjusted = true;
          }
        }
      }

      if (rangeAdjusted) {
        double adj = (numericMax - numericMin);
        plot.getRangeAxis().setLowerBound(numericMin - adj * plot.getRangeAxis().getLowerMargin());
        plot.getRangeAxis().setUpperBound(numericMax + adj * plot.getRangeAxis().getUpperMargin());
      }
    }

    int discreteValueCount = pointTimeSeriesCollection.getDiscreteValueCount();
    double interval = (numericMax - numericMin) / (discreteValueCount + 1);
    int intervalIndex = 1;

    if (pointTimeSeriesCollection.hasDiscreteData()) {
      for (int i = 0; i < pointTimeSeriesCollection.getDiscreteSeriesCount(); i++) {
        DiscreteTimeSeries dts = pointTimeSeriesCollection.getDiscreteTimeSeries(i);
        XYStepRenderer renderer = new XYStepRenderer();

        TimeSeries ts = new TimeSeries(dts.getName(), null, null);
        for (IValueTime vt : dts.getValueTimes())
          addMillisecond(
              ts,
              vt.getTime(),
              numericMin + (interval * (dts.getValueIndex(vt.getValue()) + intervalIndex)));

        if (dts.getPaint() != null) renderer.setSeriesPaint(0, dts.getPaint(), false);
        if (dts.getStroke() != null) renderer.setSeriesStroke(0, dts.getStroke(), false);

        plot.setDataset(
            numericSeriesCount + i,
            new TimeSeriesCollection(ts, pointTimeSeriesCollection.getTimeZone()));
        plot.setRenderer(numericSeriesCount + i, renderer);

        intervalIndex += dts.getDiscreteValueCount();
      }
    }

    if (from > 0) plot.getDomainAxis().setLowerBound(from);
    if (to > 0) plot.getDomainAxis().setUpperBound(to);

    if (pointTimeSeriesCollection.hasDiscreteData()) {
      // Add the value annotations.
      double annoX = plot.getDomainAxis().getLowerBound();
      intervalIndex = 1;
      for (int i = 0; i < pointTimeSeriesCollection.getDiscreteSeriesCount(); i++) {
        DiscreteTimeSeries dts = pointTimeSeriesCollection.getDiscreteTimeSeries(i);

        for (int j = 0; j < dts.getDiscreteValueCount(); j++) {
          XYTextAnnotation anno =
              new XYTextAnnotation(
                  " " + dts.getValueText(j), annoX, numericMin + (interval * (j + intervalIndex)));
          if (!pointTimeSeriesCollection.hasNumericData()
              && intervalIndex + j == discreteValueCount)
            // This prevents the top label from getting cut off
            anno.setTextAnchor(TextAnchor.TOP_LEFT);
          else anno.setTextAnchor(TextAnchor.BOTTOM_LEFT);
          anno.setPaint(
              ((AbstractRenderer) plot.getRenderer(numericSeriesCount + i)).lookupSeriesPaint(0));
          plot.addAnnotation(anno);
        }

        intervalIndex += dts.getDiscreteValueCount();
      }
    }

    // Return the image.
    ChartUtilities.writeChartAsPNG(out, chart, width, height);
  }
Example #13
0
  public String creatchat(CategoryDataset cr, int ss) {
    JFreeChart chart =
        ChartFactory.createLineChart(
            "先来先服务", "进程", "时间", cr, PlotOrientation.VERTICAL, true, true, false);
    CategoryPlot ccc = (CategoryPlot) chart.getPlot();

    // Plot plo=chart.getPlot();
    // plo.setDrawingSupplier(getSupplier());

    ValueAxis valueaxis = ccc.getRangeAxis(); // getRangeAxis();
    // 数据为整型
    valueaxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    // 设定显示范围,即总是显示1-10
    if (ss == 1) {
      Image image;
      try {
        image = ImageIO.read(new File("C:/wancheng.png"));
        chart.setBackgroundImage(image);
        chart.setBackgroundImageAlpha(1.0f);
        chart.setBorderPaint(Color.white);
        ccc.setBackgroundPaint(null);
      } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
      }

      valueaxis.setLowerBound(-1);
      valueaxis.setUpperBound(7);
    } else {
      valueaxis.setLowerBound(-1);
      valueaxis.setUpperBound(7);
    }
    CategoryItemRenderer renderer = ccc.getRenderer();
    renderer.setSeriesPaint(0, Color.YELLOW);
    renderer.setSeriesPaint(1, Color.red);
    renderer.setSeriesPaint(2, Color.green);
    renderer.setSeriesPaint(3, Color.gray);
    renderer.setSeriesPaint(4, Color.cyan);
    renderer.setSeriesPaint(5, Color.magenta);
    renderer.setSeriesPaint(6, Color.pink);

    FileOutputStream fos_jpg = null;
    try {
      if (ss == 1) {
        String chaername = "C:/jincheng.png";
        fos_jpg = new FileOutputStream(chaername);

        // 将报表保存为png文件
        ChartUtilities.writeChartAsPNG(fos_jpg, chart, 500, 510);
        return chaername;
      } else {
        String chaername = "C:/wancheng.png";
        fos_jpg = new FileOutputStream(chaername);

        // 将报表保存为png文件
        ChartUtilities.writeChartAsPNG(fos_jpg, chart, 500, 510);
        return chaername;
      }

    } catch (Exception e) {
      e.printStackTrace();
      return null;
    } finally {
      try {
        fos_jpg.close();
        System.out.println("create time-createTimeXYChar.");
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
Example #14
0
  /** チャートのイメージを直接出力する(イメージはPNG形式) */
  public void outDirectPNGChart(HttpServletResponse response) throws IOException {

    OutputStream out = response.getOutputStream();
    response.setContentType("image/png");
    ChartUtilities.writeChartAsPNG(out, chart, chartWidth, chartHeight);
  }
package com.xuyuan.chart.jfreechart.helloworld;
Example #16
0
 public void writeChartToFile(File f, int height, int width) throws IOException {
   FileOutputStream stream = new FileOutputStream(f);
   ChartUtilities.writeChartAsPNG(stream, chart, height, width);
   stream.close();
 }