How can I load Computer Directory images in JAVAFX


Question

I am trying to load my computer folder images into a wall of thumbnails. I read on a thread from another forum that ImageView "url" instance variable does not support system paths. I tried with the solution there, but it throws an exception: java.lang.OutOfMemoryError: Java heap space as it keeps reading the file.

another problem is it keeps giving me warning of using package javafx.ext -> SwingUtils.toFXImage method.

I have also tried to input the URL like that:

"file://localhost//Users/USER/Pictures/Camera/test/1.JPG"

I tried to display a number of images, but it always only displays 3 to 4 images.

I checked with the error function given from ImageView, it does not indicate that the reading of my images encountered an error.

Are there any alternatives?

Code

function load() {
    println("RUNTIME {Runtime.getRuntime().maxMemory()}");
    System.gc();
    Runtime.getRuntime().freeMemory();

    //MAC Folder PATH
    var path: String = "/Users/username/Pictures/camera/test/1.JPG";;
    var file: File = new File(path);

    //http://download.oracle.com/docs/cd/E17802_01/javafx/javafx/1.3/docs/api/javafx.ext.swing/javafx.ext.swing.SwingUtils.html

    //public toFXImage(image: java.awt.image.BufferedImage) : Image
    //Creates a JavaFX Image from a BufferedImage.
    img = SwingUtils.toFXImage(ImageIO.read(file));
}
1
7
6/23/2018 10:47:48 PM

Accepted Answer

It is not clear exactly what you are trying to do. If you are talking about JavaFX 2.0, the following code works. If you are loading a lot of images and need to conserve memory, you only have to create enough ImageView's for the number you want to display at one time. Then as you page through the images, you can swap out the Image object contained in the ImageView.

public void start(Stage primaryStage) {
    primaryStage.setTitle("Hello World");
    StackPane root = new StackPane();
    Scene scene = new Scene(root, 300, 250);

    File file = new File("/System/Library/CoreServices/loginwindow.app/Contents/Resources/LogOut.png");
    Image image = new Image(file.toURI().toString());
    ImageView iv = new ImageView(image);

    root.getChildren().add(iv);
    primaryStage.setScene(scene);
    primaryStage.show();
}
28
11/11/2011 1:15:45 AM

its simple: open a image with a browser and copy the whole url of the pic and paste it as a parameter of the Image object. DO NOT REMOVE "file///:" because this makes the image loadable. you will get your other logic from there. happy coding e.g

Image image = new Image("file:///C:/Users/Nigel/Desktop/my_image.png");
ImageView imgview = new ImageView(image);

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