This question already has answers here:
Get resource from jar
(4 answers)
Closed 9 years ago.
I have tried searching and still haven't got the solution. When I export to a jar file all my images suddenly do not work anymore. They run fine out of eclipse and I have made sure that they are in the jar file. I have tried using get resource methods and making a image-loader class to automatically go up the directory tree but it still fails. Here is what I have done:
public static Image load(String path)
{ String temp = path;
Image image = null;
try {
image = new ImageIcon(path).getImage();
}
catch ( Exception e )
{
try {
while (image == null )
{
image = new ImageIcon("../"+ path).getImage();
}
if ( path.equals("../../../../../../"+ temp))
{
while ( image ==null)
{
image = new ImageIcon("./"+ path).getImage();
}
}
}
catch ( Exception ae)
{
System.err.println("cannot locate image");
}}
return image;
}
the path I will send it look as follows: "doc/icon.png"
I have placed all my images in the doc folder, the structure is final Project, inside there is doc folder and then the src folder that contains all the packages.
Try using this:
Image.class.getClassLoader().getResource("/filepath/filename").getFile()
Instead of "Brute-force" the image path try to figure out what's the path you try to load the image from. You can look it up with the following
System.out.println("Path: " + (this.getClass().getClassLoader().getResource("")).getPath());
afterwards try to load it like this or like #Balint Bako allready sed.
Image img;
URL url = new File("the path you found out").toURI().toURL();
BufferedImage img = ImageIO.read(url);
Related
I am making a program where the user chooses an image file on their computer and it displays it in a window. I have the line of code
image = ImageIO.read(getClass().getResourceAsStream(path));
where path is the absolute path to the image. The error it returns is
Exception in thread "main" java.lang.IllegalArgumentException: input == null!
What am I doing wrong or is it not possible to get an Image outside of the project file?
So, getClass().getResourceAsStream() reads the image from default class path(either in the folder of your classes or the contents of the jar file)!
So you would want :
BufferedImage img = null;
try {
img = ImageIO.read(new File(path));
} catch (IOException e) {
}
I am trying to load an image using an InputStream. However when I load my image, it always returns null. Here is my project structure :
project
--+ src
----+ chess
------+ model
--------+ piece
----------+ Piece.java
------+ assets
--------+ icons
----------+ piece
------------+ rook_black.png
And the path I use to access the image is : ./src/chess/assets/icons/piece/rook_black.png
I have tried to show all the files in the directoryfrom Piece.java it works :
String path = "./src/chess/assets/icons/piece/";
File[] files = new File(path).listFiles();
for (File file: files) {
System.out.println(file.getName());
}
My actual code is :
public Image getImage() {
String path = "./src/chess/assets/icons/piece/rook_black.png";
InputStream image = getClass().getResourceAsStream(path);
if (image != null) {
return new Image(image);
}
System.out.println("No " + toString() + " image in " + path);
return null;
}
This code actually outputs that No rook image in ./src/chess/assets/icons/piece/rook_black.png but I want the InputStream to not be null.
The thing is you must think in terms of compiled resources, which means you must think about how the JAR artifact looks. There is no src folder.
Indeed, what you need is
final String path = "/chess/assets/icons/piece/rook_black.png";
which is an absolute path, starting from the root.
I would like to load an image from my current src directory where the java class files are located as well. However, I always get an IOException..
And how can I make sure the file gets loaded properly on Mac/Linux as well on Windows?
My code so far:
String dir = System.getProperty("user.dir") + "/Logo_transparent.png";
File imageFile = new File(dir);
BufferedImage bufferedImage = null;
try {
bufferedImage = ImageIO.read(imageFile);
} catch (IOException e) {
System.out.println(e.getMessage());
System.out.println(dir);
System.out.println();
}
IOException message:
Can't read input file!
(My path is correct - is it because of the space between Google and Drive?)
/Users/myMac/Google Drive/Privat/Programming/Logo_transparent.png
Kind regards and thank you!
I think It's because you didn't create the file, You can create the file if it doesn't exist by using this code
if(!imageFile.exists()) imageFile.createNewFile();
You're code will look like this
String dir = System.getProperty("user.dir") + "/Logo_transparent.png";
File imageFile = new File(dir);
BufferedImage bufferedImage = null;
try {
if(!imageFile.exists()) imageFile.createNewFile();
bufferedImage = ImageIO.read(imageFile);
} catch (IOException e) {
System.out.println(e.getMessage());
System.out.println(dir);
System.out.println();
}
Also you shouldn't concat child files like that instead pass it as a second argument.
File imageFile = new File(System.getProperty("user.dir"), "Logo_transparent.png");
If your image files will be packaged together with your class files (for example in the same .jar) you should not use File but read it as a resource:
bufferedImage = ImageIO.read(this.getClass().getResourceAsStream("/Logo_transparent.png"));
Notice the '/' before the file name. This means to search in the root path of the classpath.
If you specify without / it will search in the package of this (the current class)
this.getClass().getResourceAsStream("Logo_transparent.png")
You can try to build the absolute path to the image like here and read it afterward.
In the code sample below, when I test the code in Eclipse it works just fine. However, when I export the jar file and test it via the command line, it throws an error: IIOException: Can't read input file!
private BufferedImage img = null;
private String imgSource;
if (img == null)
{
try {
URL url = getClass().getResource("Images/questionMark.png");
System.out.println(url.getPath());
/* This prints: file:/C:/Users/Keno/Documents/javaFile.jar!/javaFile/Images/questionMark.png */
File file = new File(url.getPath());
img = ImageIO.read(file);
imgSource = file.getName();
} catch (IOException e) {
e.printStackTrace();
}
}
The file I want to get is located inside the Images folder which is inside the javaFile package. I've noticed one thing that may indicate the problem.
In the print statement I have, I notice an exclamation sign at the end of the javaFile.jar section. Is that correct? Could that indicate an issue with the file or structure?
Also, just in case someone has a better suggestion as to how I should load the file, I'll tell you my intentions. I would like to load the file from a relative location (Images folder) in the jar. I would like to display it (Already done in my actual code) and also store the location to be passed later on to another function (also done).
try this
public void test() {
try(InputStream is = getClass().getResourceAsStream("Images/questionMark.png")) {
ImageIO.read(is);
} catch (IOException e) {
e.printStackTrace();
}
}
You should try to check if your class is in the same directory than Images inside your jar.
|
|- Your class
|- Images
|- questionMark.png
Also, have you tried using directly your url object ?
File file = new File(url);
I'm using a simple way to get my resources for the project. I'm using Eclipse, and I have a 'res' folder to hold the needed files. This is how I load stuff, for example a 'puppy.png' just in my res folder (no subfolders):
String path = "/puppy.png";
try {
BufferedImage image = ImageIO.read(getClass().getResourceAsStream(path));
} catch(Exception ex) { ex.printStackTrace(); }
And sometimes I get an input==null error, and sometiomes not! Not like this time puppy.png loaded but next time it won't. For some classes it always loads correctly, and for the other classes I always get this error. Can anyone explain why can this happen, and how can I fix it, but still use the getResourceAsStream() method?
Please have a look at How to retrieve image from project folder?.
I have mentioned no of ways to read image from different paths.
You can try any one
// Read from same package
ImageIO.read(getClass().getResourceAsStream("c.png"));
// Read from absolute path
ImageIO.read(new File("E:\\SOFTWARE\\TrainPIS\\res\\drawable\\c.png"));
// Read from images folder parallel to src in your project
ImageIO.read(new File("images\\c.jpg"));
In your case the image must be in the same package where is the class and don't prefix /.
Note that if the resource returns null (meaning it doesn't exist), you will get this error.
Check the input returned like so:
String path = "/puppy.png";
try {
InputStream is = getClass().getResourceAsStream(path);
if (is == null) {
//resource doesn't exist
} else {
BufferedImage image = ImageIO.read(is);
}
} catch(Exception ex) { ex.printStackTrace(); }
Note that you most likely should be using String path = "puppy.png", seeing as you will already be in the content of the project folder.