以下是我的代码我使用JFree创建了直方图,我想在按钮上显示输出点击
这是标准化图像的直方图
我想这样做,点击面板上打开的jfreechart并保存在云端硬盘
请帮帮我,我是新手
代码低于..........
package org.ivb.jfreechart.barchart;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.data.xy.IntervalXYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import org.jfree.ui.ApplicationFrame;
import org.jfree.ui.RefineryUtilities;
public class Histogram extends ApplicationFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
public Histogram(final String title) throws IOException {
super(title);
IntervalXYDataset dataset = createDataset();
JFreeChart chart = createChart(dataset);
final ChartPanel chartPanel = new ChartPanel(chart);
chartPanel.setPreferredSize(new java.awt.Dimension(500, 270));
setContentPane(chartPanel);
}
private IntervalXYDataset createDataset() throws IOException {
BufferedImage imageA = ImageIO.read(new File("D://oriented.jpg"));
int[] red = new int[imageA.getHeight() * imageA.getWidth()];
int[] redhisto = new int[256];
int[] pixel;
int k = 0;
for (int y = 0; y < imageA.getHeight(); y++) {
for (int x = 0; x < imageA.getWidth(); x++) {
pixel = imageA.getRaster().getPixel(x, y, new int[3]);
red[k] = pixel[0];
k++;
}
}
for (int x = 0; x < red.length; x++) {
int y = red[x];
redhisto[y]++;
}
final XYSeries series = new XYSeries("No of pixels");
for (int i = 0; i < redhisto.length; i++)
series.add(i, redhisto[i]);
final XYSeriesCollection dataset = new XYSeriesCollection(series);
return dataset;
}
private JFreeChart createChart(IntervalXYDataset dataset) {
final JFreeChart chart = ChartFactory.createXYBarChart(
"Histogram of oriented Image", "X", false, "Y", dataset,
PlotOrientation.VERTICAL, true, true, false);
XYPlot plot = (XYPlot) chart.getPlot();
saveChart(chart);
return chart;
}
public void saveChart(JFreeChart chart) {
String fileName = "D:/histogram.jpg";
try {
ChartUtilities.saveChartAsJPEG(new File(fileName), chart, 800, 600);
} catch (IOException e) {
e.printStackTrace();
System.err.println("creating erroe during chart prepartatin");
}
}
public static void main(final String[] args) throws IOException {
final Histogram demo = new Histogram("Histogram");
demo.pack();
RefineryUtilities.centerFrameOnScreen(demo);
demo.setVisible(true);
}
}}
答案 0 :(得分:1)
不是在saveChart()
中调用createChart
,而是在按钮的Action
中执行此操作。
final JFreeChart chart = createChart(dataset);
final ChartPanel chartPanel = new ChartPanel(chart);
add(chartPanel);
add(new JButton(new AbstractAction("Save") {
@Override
public void actionPerformed(ActionEvent e) {
saveChart(chart);
}
}), BorderLayout.SOUTH);