我想从我的数组中将点图保存为图像(PNG),使用这个Java程序我可以显示我的散点图,但我不知道如何保存它。也许使用 ImageIO.write,又如何?谁能给我一些建议来解决这个问题。谢谢
public class Graph extends Application {
public void start(Stage primaryStage) {
Pane root = new Pane();
int[] mydata = {
12, 9, 0, 1, 38, 19, 21, 72, 33, 83, 14, 10, 65, 46, 10, 17, 27, 38, 65, 98, 8, 58, 38, 79, 37, 69, 26, 15};
NumberAxis xAxis = new NumberAxis();
NumberAxis yAxis = new NumberAxis();
ScatterChart scatterChart=new ScatterChart(xAxis,yAxis);
XYChart.Series data=new XYChart.Series();
for (int i=0; i< mydata.length; i++) {
data.getData().add(new XYChart.Data(i,mydata[i]));
}
scatterChart.getData().addAll(data);
root.getChildren().add(scatterChart);
Scene scene = new Scene(root, 600, 400);
primaryStage.setScene(scene);
primaryStage.show();
File file = new File("c:\\Images\\Image.png");
// and now ?????
}
public static void main(String[] args) {
launch(args);
}
}
您可以将绘图或图表绘制到像 BufferedImage 这样的图像上。之后将 BufferedImage 保存为文件。你可以尝试这样的事情:
class MyScatterPlot
{
private BufferedImage buf;
//Constructors, initializations not shown.
public void saveBufferAsImage(String pathname){
String fmt = "";
if(!(pathname == null || pathname.equals(""))){
fmt = pathname.substring(pathname.lastIndexOf(".")+1);
File outputfile = new File(pathname);
try{
ImageIO.write(buf, fmt, outputfile);
}catch(IOException ioe){System.out.println("Unable to save file");}
}
}
public void drawImage(){
buf = new BufferedImage (200, 200, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = buf.createGraphics();
g2d.fillRect(10, 10, 150, 150); //draw your image here (example only)
g2d.dispose();
}
}
要将图表另存为图像文件(例如 .png
):
MyScatterPlot plot = new MyScatterPlot();
plot.drawImage();
plot.saveBufferAsImage("MyGraph.png");
我是一名优秀的程序员,十分优秀!