Created
April 7, 2021 06:56
-
-
Save johantiden/80e9fa5acf86561520c94ac64816d68f to your computer and use it in GitHub Desktop.
javafx.scene.image.Image safer creation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import javafx.embed.swing.SwingFXUtils; | |
import javafx.scene.image.Image; | |
import javafx.scene.image.WritableImage; | |
import java.awt.image.BufferedImage; | |
import java.io.File; | |
import java.io.IOException; | |
import javax.imageio.ImageIO; | |
/** | |
* This class does two important things: | |
* | |
* 1. We must never ever call `new Image(...)` without explicitly checking for errors using Image.isError and Image.getException. | |
* This class helps us remember that this is needed. Always use this class for creating new instances of Image. | |
* | |
* 2. Avoid using com.sun.javafx.iio.jpeg.JPEGImageLoader to load images. That class uses native bindings to libjpeg which may get linked to | |
* a non-compatible version on runtime. An exception with the stacktrace below is triggered _but swallowed_ as per above. | |
* | |
* Caused by: java.io.IOException: Wrong JPEG library version: library is 80, caller expects 90 | |
* at com.sun.javafx.iio.jpeg.JPEGImageLoader.initDecompressor(Native Method) | |
* at com.sun.javafx.iio.jpeg.JPEGImageLoader.<init>(JPEGImageLoader.java:185) | |
* at com.sun.javafx.iio.jpeg.JPEGImageLoaderFactory.createImageLoader(JPEGImageLoaderFactory.java:49) | |
* at com.sun.javafx.iio.ImageStorage.getLoaderBySignature(ImageStorage.java:421) | |
* at com.sun.javafx.iio.ImageStorage.loadAll(ImageStorage.java:266) | |
* at com.sun.javafx.tk.quantum.PrismImageLoader2.loadAll(PrismImageLoader2.java:142) | |
* at com.sun.javafx.tk.quantum.PrismImageLoader2.<init>(PrismImageLoader2.java:77) | |
* at com.sun.javafx.tk.quantum.QuantumToolkit.loadImage(QuantumToolkit.java:750) | |
* at javafx.scene.image.Image.loadImage(Image.java:1060) | |
* at javafx.scene.image.Image.initialize(Image.java:799) | |
* at javafx.scene.image.Image.<init>(Image.java:702) | |
* | |
*/ | |
public class ImageUtil { | |
public static Image createImage(File file) throws IOException { | |
BufferedImage bufferedImage = ImageIO.read(file); | |
WritableImage writableImage = SwingFXUtils.toFXImage(bufferedImage, null); | |
if (writableImage.isError()) { | |
throw new RuntimeException(writableImage.getException()); | |
} | |
return writableImage; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment