How to create a JavaFX Image from an absolute path?

后端 未结 2 404
囚心锁ツ
囚心锁ツ 2020-12-12 02:43

I have an instantiated File object. I know it contains a picture format. I don\'t know where on the system the file is placed, other than the methods of F

相关标签:
2条回答
  • 2020-12-12 03:17

    File provides a method to retrieve the URL for the file and the Image constructor expects a URL String.

    Image imageForFile = new Image(file.toURI().toURL().toExternalForm());
    
    0 讨论(0)
  • 2020-12-12 03:26

    Combining the javax.imageio.ImageIO class (ref) and the javafx.embed.swing.SwingFXUtils (ref) can convert an "input" (i.e.: stream, file, URL) to a JavaFX image. Sample code (for File):

    public static Image readImage(File file) {
        try {
            BufferedImage bimg = ImageIO.read(file);
            return SwingFXUtils.toFXImage(bimg, null);
        }
        catch( IOException e ) {
            // do something, probably throw some kind of RuntimeException
        }
    }
    
    0 讨论(0)
提交回复
热议问题