簡體   English   中英

錯誤時從URL加載圖像和默認圖像

[英]Load image from URL and default image on error

我正在嘗試從URL加載圖像,這非常簡單並且效果很好。 但是,如果圖像不存在,我希望它默認為本地圖像。 我遇到的問題是它不會引發任何異常。 相反,它將不會顯示任何內容。 我假設我必須以某種方式驗證URL,但是我還要確保它是圖像而不是網頁/腳本...等

這是我的基本測試代碼。 這有效:

public class DownloadImage extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) {

        VBox root = new VBox();

        String imageSource = "https://www.wbkidsgo.com/Portals/1/Content/Hero/HeroBugsCarrot/Source/Default/WB_LT_HeroImage_Bugs_v1.png";

        ImageView imageView = new ImageView(new Image(imageSource));

        root.getChildren().add(imageView);

        primaryStage.setScene(new Scene(root, 1000, 1000));
        primaryStage.show();

    }
}

但是,如果我加載了錯誤的URL,即(Portal中為2):

String imageSource = "https://www.wbkidsgo.com/Portalss/1/Content/Hero/HeroBugsCarrot/Source/Default/WB_LT_HeroImage_Bugs_v1.png";

它只是空白。 我曾考慮過在創建映像之前創建HTTP客戶端並發送請求,但是生成HTTP客戶端需要花費幾秒鍾的時間,而我將最多加載300個左右的圖像。 我想我可以有一個http客戶端,並對每個圖像發出一個請求,然后檢查響應數據類型以查看其是否為圖像,但是還有更好的方法嗎?

您可以使用errorPropertyexceptionProperty來檢查圖像的錯誤狀態:

import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.image.Image;
import javafx.stage.Stage;

public class ImageTest extends Application {

    public static void main(String[] args) {
        launch(args) ;
    }

    @Override
    public void start(Stage primaryStage) {
        String[] urls = new String[]{
                "https://www.wbkidsgo.com/Portals/1/Content/Hero/HeroBugsCarrot/Source/Default/WB_LT_HeroImage_Bugs_v1.png",
                "https://www.wbkidsgo.com/Portalss/1/Content/Hero/HeroBugsCarrot/Source/Default/WB_LT_HeroImage_Bugs_v1.png"
        } ;

        for (String url : urls) {
            Image image = new Image(url);
            if (image.isError()) {
                System.out.println("Error loading image from "+url);
                // if you need more details
                // image.getException().printStackTrace();
            } else {
                System.out.println("Successfully loaded image from " + url);
            }
        }
        Platform.exit();
    }

}

給出以下輸出:

Successfully loaded image from https://www.wbkidsgo.com/Portals/1/Content/Hero/HeroBugsCarrot/Source/Default/WB_LT_HeroImage_Bugs_v1.png
Error loading image from https://www.wbkidsgo.com/Portalss/1/Content/Hero/HeroBugsCarrot/Source/Default/WB_LT_HeroImage_Bugs_v1.png

您可以使用ImageView.setImage()方法更改圖像。 我建議使用您的默認圖像以BufferedImage的形式初始化ImageView ,然后在以后使用實際圖像進行設置。 您可以使用ImageIO從文件系統或類路徑中加載它。

至於實際的圖像,我還將使用ImageIO將URL加載為BufferedImage 這將引發IOException ,因此,如果發生錯誤或未鏈接到受支持的圖像類型,則不會發生任何事情。

如果您對線程和並發性了解很多,我會將圖像加載到另一個線程上,這樣就不會凍結您的主線程。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM