Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load Image file to ImageView?

I am attempting to display an image file as soon as it is selected from a file chooser. The file chooser is restricted to .png and .jpg files with the selected files being stored in a variable of type File. To do this I have set up an ImageView, and I wish to set the image with this new file only problem is it is of type File not Image.

How can this be achieved? Code so far...

    public void fileSelection(){

        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("Select Profile Picture");
        fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("Image Files", "*.png", "*jpg"));
        File selectedFile = fileChooser.showOpenDialog(null);
        File selectedFileInput = selectedFile;

        if(selectedFile != null) {
            selectedFileOutput.setText("File selected: " + selectedFile.getName());
            previewPicture.setImage();
        } else {
            selectedFileOutput.setText("Please select a profile picture...");
        }
    }
like image 283
Philayyy Avatar asked Oct 19 '16 00:10

Philayyy


2 Answers

You can simply create an image with

Image image = new Image(selectedFile.toURI().toString());

and then place it in the ImageView:

previewPicture.setImage(image);

Other constructors offer more control over resources required for loading the image. If you want to force the image to be a certain size, you can resize it on loading, which will save memory if the user chooses a large image but you only want to display a scaled-down version. Additionally, loading a large image may take time, so you should not load it on the UI thread. The Image constructors taking string versions of URLs have options to automatically load the image in a background thread. The following forces the width and height to be both no more than 240 pixels (while maintaining the original aspect ratio), and loads the image in the background (thus not blocking the UI):

Image image = new Image(selectedFile.toURI().toString(),
    240, // requested width
    240, // requested height
    true, // preserve ratio
    true, // smooth rescaling
    true // load in background
);

See the documentation for other available constructors.

like image 95
James_D Avatar answered Sep 30 '22 19:09

James_D


You create image and set to the ImageView as follows

  Image image = new Image(new FileInputStream(selectedFile));
  previewPicture.setImage(image);
like image 41
ravthiru Avatar answered Sep 30 '22 21:09

ravthiru