Search code examples
javajavafxsave-image

Getting Black Image when saving a JavaFX snapshot


I have set up a background Task that waits several seconds after a given Panel/Chart become visible. That is performed by running a sleep on a background non-GUI thread and then upon waking up it runs a

Platform.runLater

to create the snapshot and image.

Before the real 'action' for saving the image occurs we can see the window come up:

enter image description here

While that image is rendering we have the background code that has been put to sleep by a Task. After 5000 millis that background task wakes up and launches a Platform.runLater to save the scene/pane/chart to a file.

Here is the snapshot and image code:

All this happens on a background thread via a Task submitted to a ThreadPool

    Thread.sleep(5000)   // Wait for images to be rendered -
              // they are visually confirmed to be available at  about 1000 ms actually
    javafx.application.Platform.runLater(new Runnable() {
      override def run() = {
//            val snapShot = chart.snapshot(null)
//            val snapShot = scene.snapshot(null)
        val snapShot = pane.snapshot(null,null)
        ImageIO.write(SwingFXUtils.fromFXImage(snapShot, null),
          "jpg", new File(fileName))

As you can see (from the commented out lines) - I have confused about which object to use for creating the snapshot: all three above have been attempted:

  • Chart
  • Scene
  • Pane

Always the result is a Black Image. OOC I also tried changing the background color via

snapshotParameters.setFill(Color.WHITE)

That had no effect.

enter image description here

What is the correct procedure ?

Update I also tried a callback approach:

        pane.snapshot(  // Also tried scene and chart here ..
        new Callback[SnapshotResult, Void]() {
          override def call(result: SnapshotResult): Void = {
            ImageIO.write(SwingFXUtils.fromFXImage(result.getImage, null),
              "jpg", new File(fileName))
            latch.countDown
            null
          }
        },p,null)

Likewise - still a Black Image.


Solution

  • After all that .. the answer is that "jpg" is simply not working. "png" format works fine.