Search code examples
javajavafxfilechooser

JavaFX: Get image from FileChooser and save it in a byte[]


I want to select an image using FileChooser and then save the selected image in a byte[] variable, I open the dialog

FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Open Resource File");
fileChooser.showOpenDialog(new Stage());

Now, How can I get the image file from FileChooser and save it in byte[] variable?


Solution

  • You can use Files.readAllBytes(Path path):

    FileChooser fileChooser = new FileChooser();
    fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("PNG", "*.png"));
    File pngImage = fileChooser.showOpenDialog(window);
    if (pngImage != null) {
        try {
            byte[] imageBytes = Files.readAllBytes(pngImage.toPath());
        } catch (IOException e) {
            System.err.println("File couldn't be read to byte[].");
        }
    }
    

    An alternative: IOUtils:

    byte[] bytes = IOUtils.toByteArray(new FileInputStream(pngImage));