[英]Java ImageIO.read(URL) returning null when it shouldn't
好的,所以我花了大約15個小時來解決這個問題。 我正在將此程序導出到不可運行的jar文件中。 問題是我試圖將圖像加載到jar中並將其設置為變量。
我看過其他帖子,我想我已經盡力找到了所有可以找到的東西,但似乎沒有任何效果。
我不是在問如何查找圖像,因為我可以獲得圖像的URL,但是ImageIO.read(URL)不會引發任何異常,而是返回null。 該圖像是我聽說過的.png與ImageIO.read()兼容。 我正在使用一個API,所以log()行是什么。
任何幫助表示贊賞。 謝謝!
我的項目:
Project
->src
-->package
--->Main.java
--->paint.png
我的代碼:
在我的主要方法中:(mainPaint是私有圖像)
mainPaint = getImage("paint.png");
方法:
private Image getImage(String fileName) {
URL url = getClass().getResource(fileName);
BufferedImage image = null;
log(url.toString()); // To make sure I have the correct file
// returning jar:file:/C:/Users/Me/MyJar.jar!/package/paint.png
try {
image = ImageIO.read(url);
} catch (IOException e1) {
log("Error converting url to image.");
// This is not happening
}
if (image == null) {
log("Image is null.");
// This is happening
}
return image;
}
網址無效嗎? 我只是想念什么嗎? 我只是想將本地圖像保存在jar中作為Image對象,我覺得這對我想做的事情來說太困難了。
編輯:我也只是試圖使mainPaint一個BufferedImage並使用:
Image image = Toolkit.getDefaultToolkit().getImage(getClass().getResource(fileName));
if(image == null) {
log("Image is null");
}
log("Height: " + image.getHeight(null));
log("Width: " + image.getWidth(null));
BufferedImage bimage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB);
// Draw the image on to the buffered image
Graphics2D bGr = bimage.createGraphics();
bGr.drawImage(image, 0, 0, null);
bGr.dispose();
// Return the buffered image
return bimage;
圖片的高度和寬度返回-1?
ImageIO.read()將僅加載GIF,PNG,JPEG,BMP和WBMP圖像類型。 任何其他圖像類型都將返回null且沒有錯誤。
它可以回答您的問題。
ImageIO.read()
將不會加載SVG文件,因此,如果您的圖像位於SVG formate中,則需要向其添加插件以支持SVG
這是另一篇SO帖子,解釋了在哪里可以做到這一點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.