【问题标题】:JavaFX: Get image from FileChooser and save it in a byte[]JavaFX:从 FileChooser 获取图像并将其保存在一个字节 []
【发布时间】:2020-05-02 15:04:13
【问题描述】:

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

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

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

【问题讨论】:

    标签: java javafx filechooser


    【解决方案1】:

    你可以使用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));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-07
      相关资源
      最近更新 更多