簡體   English   中英

JavaFX-無法加載圖片網址

[英]JavaFX - image url not loading

代碼行nr.2正在工作,但是我無法獲取代碼nr.1來工作。 它什么也沒顯示。

1)圖片image = new Image(“ https://www.countryflags.io/no/shiny/64.png ”);

2)圖片image = new Image(“ file:/Users/macbookpro/Desktop/64.png”);

img1.setImage(圖像);

的System.out.println(image.getWidth());

您是否嘗試打印圖像引發的異常? 這似乎是這樣:

java.io.IOException: Server returned HTTP response code: 403 for URL: http://www.countryflags.io/no/shiny/64.png

僅當將error屬性設置為true時,getException()方法才包含非null值,在這種情況下,它包含導致圖像加載失敗的異常。

有關403響應代碼的更多信息,請查看此鏈接https://httpstatuses.com/403

更新 :您可以通過以下方式使其通過瀏覽器(例如Firefox)模擬對URL的訪問:

String imgUrl = "https://www.countryflags.io/no/shiny/64.png";
URLConnection connection = new URL(imgUrl).openConnection();
connection.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:25.0) Gecko/20100101 Firefox/25.0");
Image image = new Image(connection.getInputStream());

這樣,您應該能夠加載圖像,並且實際上image.isError()將返回false。

暫無
暫無

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

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