How to convert file to image for display in ImageView in java?

I am trying to display an image file as soon as it is selected from a selection file. File selection is limited to .png and .jpg files with selected files stored in a variable of type File. To do this, I created an ImageView, and I want to install an image with this new file, only the problem is the File not Image type.

How can this be achieved? The code is still ...

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...");
        }
    }
+4
source share
2 answers

You can simply create an image using

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

and then put it in ImageView:

previewPicture.setImage(image);

, . , , , , , . , , . Image, URL-, . 240 ( ) ( , ):

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

.

+6

ImageView

  Image image = new Image(new FileInputStream(selectedFile));
  previewPicture.setImage(image);
+1

Source: https://habr.com/ru/post/1658141/


All Articles