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

Abd*_*rif 1 java javafx filechooser

我想选择一个图像FileChooser,然后将所选图像保存在 byte[] 变量中,我打开对话框

FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Open Resource File");
fileChooser.showOpenDialog(new Stage());
Run Code Online (Sandbox Code Playgroud)

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

M. *_* S. 5

您可以使用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[].");
    }
}
Run Code Online (Sandbox Code Playgroud)

另一种选择IOUtils

byte[] bytes = IOUtils.toByteArray(new FileInputStream(pngImage));
Run Code Online (Sandbox Code Playgroud)