JavaFX 图像:检查图像是否有效

JavaFX Image: Check if image is valid

我编写了一个具有许多配置的小型 JavaFX 应用程序。其中之一是,您可以在配置文件中定义要使用的图像。

现在我想为每种情况添加错误处理,但我不知道如何检查特定图像是否可绘制。

我已经知道如何检查图像是否存在,现在我只想知道如何检查 javafx 是否会绘制我的图像或什么也不做。

Image img = new Image("file:corrupted.png");
gc.drawImage(img, 0, 0);

在这种情况下,不会抛出任何异常,gc 也不会绘制任何内容。

if (!img.isValid()) {
    throw new IllegalArgumentException;
}

我想做类似上面代码的事情

可以在加载 Image 期间检测错误。

来自Image.errorProperty()

Indicates whether an error was detected while loading an image.

如果您需要知道导致错误的原因,您可以使用:

来自 Image.exceptionProperty():

The exception which caused image loading to fail. Contains a non-null value only if the error property is set to true.

如果您的 Image 是使用在后台加载的构造函数重载构造的,那么您还可以使用 Image.progressProperty() 检查图像是否已完成加载。如果image.getProgress() == 1 && !image.isError()true,那么你可以确定有一个有效的图像。