JavaFX convert WritableImage to Image


Question

I am doing some application which makes a screenshot of LineChart and save it to pdf. So I don't know a smooth way to convert WritableImage (JavaFX 2.2) to Image (iText lib).

My temporary solution is

  • to make a snapshot, then
  • get the WritableImage from that snapshot
  • write the image to a png file
  • open image and make iText object Image

I would like to make some changes: I don't want to write the png file to disc, I just want the snapshot to be written to a pdf.

My temp solution is:

 WritableImage wim = new WritableImage((int) lineChart.getWidth(),(int) lineChart.getHeight());
 Scene scena = primaryStage.getScene();
 scena.snapshot(wim);

 File fileA = new File("C://Graphs/chart.png");
 try {
      ImageIO.write(SwingFXUtils.fromFXImage(wim, null), "png", fileA);
 }
 catch (Exception s) {
 }
 pdfDocument.add(preface3);
 com.itextpdf.text.Image graph =com.itextpdf.text.Image.getInstance("C://Graphs/chart.png");
 pdfDocument.add((com.itextpdf.text.Element) graph);        
1
6
9/11/2018 8:10:19 PM

Accepted Answer

Use:

ByteArrayOutputStream  byteOutput = new ByteArrayOutputStream();

ImageIO.write( SwingFXUtils.fromFXImage( wim, null ), "png", byteOutput );

com.itextpdf.text.Image  graph;
graph = com.itextpdf.text.Image.getInstance( byteOutput.toByteArray() );
9
12/19/2013 4:57:36 PM

My task was to copy drawing from Canvas, it will copy to WritableImage, than get Image from WritableImage (for me it was coping to Clipboard). This Image you can process as you want.

        WritableImage wi = new WritableImage((int)gc.getCanvas().getWidth(), 
                (int)gc.getCanvas().getHeight());
        gc.getCanvas().snapshot(null, wi); //Coping all that now in Canvas
        //gc is GraphicContext object from Canvas, it has drawing functions
        BufferedImage bi =SwingFXUtils.fromFXImage((Image)wi, null); 
        SwingFXUtils.toFXImage(bi, (WritableImage)image);

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon