Reputation: 1614
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
?
Upvotes: 2
Views: 5193
Reputation: 82461
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());
Upvotes: 8
Reputation: 40298
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
}
}
Upvotes: 1