I'm trying to load an image from an executable JAR file.
I've followed the information from here, then the information from here.
This is the function to retrieve the images:
public static ImageIcon loadImage(String fileName, Object o) {
BufferedImage buff = null;
try {
buff = ImageIO.read(o.getClass().getResource(fileName));
// Also tried getResourceAsStream
} catch (IOException e) {
e.printStackTrace();
return null;
}
if (buff == null) {
System.out.println("Image Null");
return null;
}
return new ImageIcon(buff);
}
And this is how it's being called:
logo = FileConverter.loadImage("/pictures/Logo1.png", this);
JFrame.setIconImage(logo.getImage());
With this being a simple Object.
I'm also not getting a NullPointerException unless it is being masked by the UI.
I checked the JAR file and the image is at:
/pictures/Logo1.png
This current code works both in eclipse and when it's been exported to a JAR and run in a terminal, but doesn't work when the JAR is double clicked, in which case the icon is the default JFrame icon.
Thanks for you're help. It's probably only me missing something obvious.
I had a similar problem once, which turned out to be down to issues relative addressing and my path being in the wrong place somehow. I dug this out of some old code I wrote that made it use an absolute path. That seemed to fix my problem; maybe it will work for you.
String basePath = (new File(".")).getAbsolutePath();
basePath = basePath.substring(0, basePath.length()-1);
FileConverter.loadImage(basePath+"/pictures/Logo1.png", this);
Related
So we got this assignment in a basic java programming course and we're supposed to implement a kind of card deck. To help us with this they have given us resources that will present a GUI on the screen, but when running my program I get a IOException that says that it can't read the input file, most likely since the pathname is wrong. And I dont know how to fix it, we're not even supposed to be in meddling with this code. The error is thrown in this method:
private Image getImg(Card aCard) {
File pathToFile = null;
if (aCard == null) {
pathToFile = new File("cardset-oxymoron/shade.gif");
} else {
String suits = "cdhs";
char c = suits.charAt(aCard.getSuit());
String fileName = String.format("%s/%02d%c.gif", "cardset-oxymoron", aCard.getRank(), c);
pathToFile = new File(fileName);
}
Image img = null;
try {
img = ImageIO.read(pathToFile);
} catch (IOException ex) {
System.err.println("Failed to create image");
ex.printStackTrace();
}
return img;
}
And according to the error stack(?) it is at line 99, which is the
img = ImageIO.read(pathToFile);
line
The folder that the cards are in is inside the project folder, right in between bin and src. using IntelliJ debugger I can see that the the pathToFile is "cardset-oxymoron\02d.gif". The filename is correct as all the cards are "[01-13][c/d/h/s].gif". When I rightclicked and copied the path to the files inside IntelliJ it was using forwardsslashes and not backslashes. But then I checked in explorer and it was the other way around... I have no idea where this is going wrong, any input would be greatly appreciated!
According to your code your files are in directory cardset-oxymoron relative to your JVM run directory. I'm not sure about IntelliJ (I work all the time with Eclipse and Maven), but it could be bin directory.
You can check it by put those 2 lines to see what is it actually (somewhere before your actual code)
File currentDir = new File("./");
System.out.println(currentDir.getAbsolutePath());
Then your cardset-oxymoron must be in that directory. Or you can change file path appropriately.
E.g. if currentDir is bin then pathToFile will be
pathToFile = new File("../cardset-oxymoron/shade.gif");
as well as fileName for other case.
I try building a texture class for LWJGL 3 in Java.
My loadTexture function looks like this:
public static Texture loadTexture(String filename) {
int id = -1;
try {
File texture = new File(filename);
if (!texture.exists()) {
System.err.println("File '" + filename + "' does not exist.");
return null;
}
// crash in following line
InputStream stream = ClassLoader.getSystemResource(filename).openStream();
PNGDecoder decoder = new PNGDecoder(stream);
// Some code between here
return new Texture(id, new Vector2i(decoder.getWidth(), decoder.getHeight()));
} catch (IOException e) {
e.printStackTrace();
return new Texture(id, new Vector2i());
}
}
The stacktrace is following:
Exception in thread "main" java.lang.NullPointerException
at org.citynopolisproject.graphics.Texture.loadTexture(Texture.java:49)
at org.citynopolisproject.Game.<init>(Game.java:30)
at org.citynopolisproject.Game.<init>(Game.java:33)
at org.citynopolisproject.Game.main(Game.java:188)
The location of the file is: citynopolisproject/res/splash.png and the source file of the Texture.java (if needed) is stored in citynopolisproject/src/org/citynopolisproject/graphics.
But I don't get why it crashes and throws a NPE.
You have any ideas?
Greetings
The issue (I suspsect) is that ClassLoader.getSystemResource(filename) is returning null. This could be because the file you are looking for is not on the classpath or because the classloader can't find the resource by the name you reference it.
In order to help we'd need to know more about the structure of your project. Where is this file you are looking for and is this being run in a Jar file?
You may need to look up more info on how to reference resources on the classpath. And remember that once you build the jar you wont be able to reference it with new File(filename) normally.
EDIT
You most likely do not want to bypass getting your resource from that classpath. If you are ever going to jar this program then you should be using something that will work even after it has been jarred.
I wonder if anyone could help? I have been developing a java app which displays images from disk on a jframe.
Using netbeans I have created a java package called images within my project and stored the images in that package. First off is that the way I should do it If I want them to ship with the app?
I have the following function to read the image:
Image readImg(String file)
{
Image image = null;
try {
File imgFile = new File(file);
image = ImageIO.read(imgFile);
} catch (IOException e) {
// System.out.println("Can not Display Image");
e.printStackTrace();
}
if (image != null){
return image;
} else{
return null;
}
}
My problem comes that I cannot work out the relative filepath to pass to the function. I have got the image to display calling it like so:
Image headerImg = readImg("C:\\Users\\D#nb0y\\Documents\\NetBeansProjects\\GiftAidApp\\src\\images\\galogo.png");
Obviously this will completely fall apart if the app is run on any other device. Can anyone give me a heads up as to making this code portable?
thanks very much
Since it's a JFrame you're trying to add an image to, it might be better to use an ImageIcon instead of an Image.
Try this:
ImageIcon image = new ImageIcon("images/galogo.png");
JLabel imageLabel = new JLabel(image);
frame.add(imageLabel);
This should make the app portable as well if you include you images folder along with your project.
I am a new programmer to Java. I have a made a small Directory Application that I would like to export, but for some reason, whenever I try to export it to a runnable jar file, the result doesn't contain any of the images I specified within my program. Basically, I ran it in eclipse, and it worked fine, but when I ran it as an runnable JAR, it has no images. I have 5 .java files that are all bundled with eachother. My Images are found at Images/Image.png [I already made The Images folder a source folder.]
I have tried eveything, but for some reason i can't get it to work, if you have any knowledge on the topic, please tell me. I don't know if its because I'm a noob or something I'm doing wrong.
static ImageIcon logoicon = new ImageIcon("Images/Logo.png");
Here is the method I use:
public static ImageIcon createImageIcon(final String path) {
InputStream is = ImageLoader.class.getResourceAsStream(path);
int length;
try {
length = is.available();
byte[] data = new byte[length];
is.read(data);
is.close();
ImageIcon ii = new ImageIcon(data);
return ii;
} catch (IOException e) {
LogManager.logCriticalProblem("Image not found at {} - {}", new Object[]{path, e.getMessage()});
}
return null;
}
If you have problems with this method, try altering the path you're using:
"Images/Logo.png"
"/Images/Logo.png"
"src/Images/Logo.png"
"/src/Images/Logo.png"
Or other combinations depending on your package structure. For example, if your images are actually in net.blah.fizz.Images, your path would be "/net/blah/fizz/Images/image.png"
Did you try getResourceAsStream() method ? Checkout this page for more information
I'm new here and kinda new to java.
I've encountered a problem.
I have a very simple program that tries to create pngs and save them in a user selected folder.
byteimage is a a private byte[]:
byteimage = bcd.createPNG(300, 140, ColorSpace.TYPE_RGB, Color.BLACK, Color.BLACK);
setPath() is called inside the action listener of the browse button
private void setPath() {
JFileChooser pathchooser = new JFileChooser();
pathchooser.setMultiSelectionEnabled(false);
pathchooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
pathchooser.setApproveButtonMnemonic(KeyEvent.VK_ENTER);
pathchooser.showDialog(this, "OK");
File f = pathchooser.getSelectedFile();
if (f != null) {
filepath = f.getAbsolutePath();
pathfield.setText(filepath);
}
}
Byte to png method looks like this:
public void byteToPNG(String filename) {
try {
InputStream in = new ByteArrayInputStream(byteimage);
BufferedImage bufferedimg = ImageIO.read(in);
ImageIO.write(bufferedimg, "png", new File(filename));
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
This method is called like this:
byteToPNG(pathfield.getText() + System.getProperty("file.separator") + textfield.getText() + ".png");
textfield.getText() sets the actual name of the png.
Inside the constructor, default filepath is set:
filepath = System.getProperty("user.dir");
pathfield.setText(filepath);
The code runs fine from Eclipse and it produces a png image at the desired location.
Unfortunately, after exporting as jar, it starts but when the button for generating the png is pressed, nothing happens. I'm thinking there's a problem at InputStream or BufferedImage, but I'm a bit puzzled.
If the String fileName passed to byteToPNG isn't absolute (i.e. written in the form "C:/foo/bar/etc") that could be the cause of the broken jar. You could also try running the jar file in the terminal using the command:
java -jar myJarFile.jar.
This will cause a console window to remain open alongside your running jar application in which all your applications output (including any exceptions) will be printed.