How to create a JavaFX Image from an absolute path?

时光毁灭记忆、已成空白 提交于 2019-12-17 21:33:42

问题


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 File available to me getPath(), getAbsolutePath() etc.

My question is: how can I instantiate a JavaFX Image object with the picture in my File?


回答1:


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());



回答2:


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
    }
}


来源:https://stackoverflow.com/questions/37521378/how-to-create-a-javafx-image-from-an-absolute-path

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!