JavaFX:从 FileChooser 获取图像并将其保存在字节 [] 中

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

我想使用 FileChooser select 图像,然后将 selected 图像保存在 byte[] 变量中,我打开对话框

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

现在,如何从 FileChooser 获取图像文件并将其保存在 byte[] 变量中?

您可以使用 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[].");
    }
}

备选方案:IOUtils

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