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...");
}
}
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.