1

While trying to load images from URLs there was some strange behavior in the image size being inconsistent the images only have full size if loaded in background and then waiting for the progress. To analyze the situation i created the JUnit test below. The expected size in background mode is not consistent with the size of the loaded images.

Why does the image size depend on whether the image is loaded in background or not?

 @Test
  public void testImage() throws InterruptedException {
    // do not exit on close of last window
    // https://stackoverflow.com/a/10217157/1497139
    Platform.setImplicitExit(false);
    /// https://stackoverflow.com/a/38883432/1497139
    // http://www.programcreek.com/java-api-examples/index.php?api=com.sun.javafx.application.PlatformImpl
    com.sun.javafx.application.PlatformImpl.startup(() -> {
    });
    String urls[] = {
        "https://upload.wikimedia.org/wikipedia/commons/thumb/b/ba/Flag_of_Germany.svg/320px-Flag_of_Germany.svg.png",
        "https://via.placeholder.com/50x50" };
    int expectedWidth[][] = { { 160, 25 }, { 320, 50 } };
    int expectedHeight[][] = { { 96, 251 }, { 192, 50 } };
    boolean backgrounds[] = { false, true };
    int i = 0;
    for (boolean background : backgrounds) {
      int j=0;
      for (String url : urls) {
        Image image = new Image(url, background);
        assertNotNull(image);
        if (background)
          while (image.getProgress() < 1)
            Thread.sleep(40);
        assertEquals("w " + i+ ","+j, expectedWidth[i][j], image.getWidth(), 0.1);
        assertEquals("h " + i+ ","+j, expectedHeight[i][j], image.getHeight(), 0.1);
        j++;
      }
      i++;
    }
  }
Wolfgang Fahl
  • 15,016
  • 11
  • 93
  • 186
  • please note that I get different result in a travis environment. My own environment is MacOS – Wolfgang Fahl Sep 01 '18 at 18:32
  • I think the framework doesn't know the actual size of image till it's fully loaded so you can easily check if it's loaded or not and act upon – Ahmed Emad Sep 01 '18 at 18:35
  • My assumption is that in any case the image is fully loaded - either since the loading is not in background or since the loop in the code waits for the image to be fully loaded. What is wrong with that assumption? – Wolfgang Fahl Sep 01 '18 at 18:37
  • sorry I didn't get what you say but you can use listener on the background flag without loop which will stop the UI thread and make the application stop which is bad for your user – Ahmed Emad Sep 02 '18 at 11:44

0 Answers0