2016-04-19 160 views
1

我想從我的數組中保存一個點圖作爲圖像(PNG),通過此Java程序,我可以顯示我的Schatter圖,但我不知道如何保存它。也許用ImageIO.write,以及如何? 任何人都可以給我一些建議來解決這個問題。謝謝保存圖片爲PNG

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); 
} 
} 

回答

0

可以繪製你的圖或圖表上類似的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"); 
+0

謝謝\t 我怎樣才能增加我的圖表?如果我設置場景scene = new Scene(root,1000,500);我變得一樣大小。 – Lolitta

+0

您可以在繪製圖形時相應地縮放圖形。只需添加一些計算,例如根據屏幕設置一個比例。 – user3437460

0

您如上所述here,還需要編寫代碼:

... 
//and now 
WritableImage image = scatterChart.snapshot(new SnapshotParameters(), null); 
try { 
    ImageIO.write(SwingFXUtils.fromFXImage(image, null), "png", file); 
} catch (IOException e) { 
    // TODO: handle exception here 
}