Images are not running in .jar - java

I'm making a Java project, and now that it is finished, i want to make a .jar version.
But when i run the .jar version, the images are not included. I'm working with Netbeans on Mac.
I try to make this code :
private static String chemin = System.getProperty("user.dir");
private String fond_path = chemin+"/src/hepta/Images/FondParametres.png";
fondPanels = new ImageIcon(fond_path);
But it looks like not working in the .jar version, even if the images are at the same place than before !
My questin is, why is it different because the path is available ?
(I precise that i make some researches, to find some codes like this :
URL imageurl = getClass().getResource("/images/images2.gif");
Image myPicture = Toolkit.getDefaultToolkit().getImage(imageurl);
JLabel piclabel = new JLabel(new ImageIcon( myPicture ));
but i don't really understand the difference)
Thanks !

The difference is, the first is a file reference. The path points to a file within the file system.
The second is a resource reference, that points to a entry within a zip file, that Java knows how to read.
When you look at the folder that contains the .jar file, you will not there is no directory src/hepta/Images. This means if you were to try and use the file reference, Java would be unable to locate the file in question.
Instead, you need to tell Java to look up the resource, based on it's class path/search path, which points to a resource that has been embedded inside the .jar file - which is just a zip file with some extras...

Related

Eclipse export isn't showing images properly [duplicate]

When running a Java app from eclipse my ImageIcon shows up just fine.
But after creating a jar the path to the image obviously gets screwed up.
Is there a way to extract an image from the jar at runtime so I can then open it up? Or, is there a better way to do this?
I'd like to distribute a single jar file if possible.
To create an ImageIcon from an image file within the same jars your code is loaded:
new javax.swing.ImageIcon(getClass().getResource("myimage.jpeg"))
Class.getResource returns a URL of a resource (or null!). ImageIcon has a constructors that load from a URL.
To construct a URL for a resource in a jar not on your "classpath", see the documentation for java.net.JarURLConnection.
You can try something like:
InputStream stream = this.getClass().getClassLoader().getResourceAsStream("/images/image.jpg");
In your JAR file, you might have a directory structure of:
MyJAR.jar
- com (class files in here)
- images
----image.jpg
This is working for me to load and set the content pane background image:
jar (or build path) contains:
- com
- img
---- bg.png
java contains:
JFrame f = new JFrame("Testing load resource from jar");
try {
BufferedImage bg = ImageIO.read(getClass().getResource("/img/bg.png"));
f.setContentPane(new ImagePanel(bg));
} catch (IOException e) {
e.printStackTrace();
}
Tested and working in both jar and unjarred (is that the technical term) execution.
BTW getClass().getClassLoader().getResourceAsStream("/img/bg.png") - which I tried first - returned me a null InputStream.
In netbeans 8.1 what I've done is to include the folder of icons and other images called Resources inside the src folder in the project file. So whenever i build Jar file the folder is included there.The file tree should be like this:
src (Java files in source packges are here)
** PACKAGE YOU NAMED IN PROJECT**
file.java
Resources
image.jpg
The code should be like:
jToggleButton1.setIcon(new javax.swing.ImageIcon(this.getClass().getResource("/resources/image.jpg")));
Load image in from Jar file during run time is the same as loading image when executed from IDE e.g netbeans the difference is that when loading image from JAR file the path must be correct and its case sensitive (very important).
This works for me
image1 = new javax.swing.ImageIcon(getClass().getResource("/Pictures/firstgame/habitat1.jpg"));
img = image1.getImage().getScaledInstance(lblhabitat1.getWidth(), lblhabitat1.getHeight(), Image.SCALE_SMOOTH);
lblhabitat1.setIcon(new ImageIcon(img));
if p in "/Pictures/firstgame/habitat1.jpg" is in lower case it wont work. check spaces, cases and spelling

Cannot Construct An Image Object With Relative File Path WIthout Using file: Prefix

I have been trying to create an image object like this:
Image img = new Image("images/jack.png");
or
Image img = new Image("jack.png");
or /jack.png or /images/jack.pngetc.
I have looked up the working directory using System.getProperty("user.dir") and it is indeed where I put my image file. When I use file: prefix, it does work, like so:
Image img = new Image("file:images/jack.png");
However, it is also supposed to work without using it. In the textbook it is done without file:. I've seen other codes that work without it.
At the end of a bunch of chained exceptions, it says:
Caused by: java.lang.IllegalArgumentException: Invalid URL or resource not found
I also tried to read source code from OpenJDK and I could figure anything out because many methods were native and from what I traced I didn't understand how it didn't work. Also, I can create files the same way, I just can't create images. For instance, this works:
File file = new File("fileName.txt");
What causes this problem, what should I do to fix it?
I'm using NetBeans, if that matters.
Note that System.getProperty("user.dir") does not return the working directory. It returns the user directory.
A path relative to the working directory can be specified using a relative file path in the File constructor. However it's bad practice to rely on the working directory. Starting the application from NetBeans results in the working directory being the project directory, but this is not the case, If started in a different way.
Images you need in your application should therefore be added to the jar.
In this case you can retrieve the image URL via Class.getResource(). (convert to String using toExternalForm().)
If you have a File that references a image file, you can use the File instance to get a URL:
File file = ...
String urlString = file.toURI().toURL().toExternalForm();
Those URLs can be used with the Image constructor.
Note that
File file = new File("fileName.txt");
does not create a file. It just represents a file path. This file may or may not exist. Simply invoking the File constructor does not create a new one.
File file = new File("name.txt");
creates a file somewhere. It doesn't read the existing file whereas
Image image = new Image("pathToImage.png");
tries to read the existing image. In order to be able to read an image stored somewhere you need either the absolute path, which requires the protocol (http, file, ftp etc.) or you put your image into the 'known' directory, like the resources dir of your project.
Say, you have your java sources under src/main/java. The resources dir could be src/main/resources. Put your image there and try working with relative path relative to src/main/resources.

Java: Reading in an image from same folder as java files

I have code that reads in an image file from the same directory as the java files, but currently I can only get it to work if the entier path is given.
picture = new JLabel(new ImageIcon(ImageIO.read(new File("C:\\Users\\...\\ogre.png"))));
The image is in the same folder as the java files. But when I try just "ogre.png" or ".\\ogre.png" or similar it does not work.
My question is this:
I will be exporting to a JAR eventually, will this affect that once the jar is created? (I'm assuming yes, since creating a jar doesnt change the source code).
How can I read the file from the same folder instead of the exact file path, In a situation where the containing folder were to be moved for example.
This is the standard way... (and it will work when everything is in the jar)
URL url = OneOfYourClass.class.getResource("package/pathTo/image/ogre.png");
ImageIcon image = new ImageIcon(url);
OneOfYourClass is a class that you have (maybe the main class)
package/pathTo/image/ is the path from this class to find your image

Avoid full file paths when importing files

Trying to read an image into java, currently what I have to do is this:
Image img = new Image("file:E:/Javaworkspace/Project/src/resource/image.png");
However, I am not the only one going to be working on that project and this path works only in my machine. I did try
Image img = new Image("file:/resource/image.png")
but this leads to FileNotFound. I don't know what this thing is called in English, I hope you understand what I am trying to convey here.
EDIT:
I added the folder "resource" via Build Path now and am trying to get input stream as such:
ImageView imgView = new ImageView(new Image(this.getClass().getResourceAsStream("/resource/image.png")));
Needless to say, I get a NullPointerException, which according to the documentation, occurs when the path doesn't exist. How can it not exist after I specifically created it via Build Path, it exists in CLASSPATH. (Yes, the file is there too or can I not simply copy it into the folder? )
Place the image inside the project folder rather than using file system to access the file. Then you can use this:
Image image = ImageIO.read(getClass().getResourceAsStream("/resource/image.png"));
to get the image file where ever required by anyone.
I believe you can always try user.home but then if one person updates an image or adds one it won't update for you.
Image img = this.getClass().getResource("/resource/image.png");
Probably messed up parentheses
Also make sure you have folder "resource" in right folder (most likely same folder src and out are in

Java - How To Set An Image Path Without Using The C:\\ Direcory

I created a java app and I put some images in it and even gave it an image icon as the desktop image, but when i made it a jar file, and put it on another pc, all images were gone. This is the image path :
File imageFile = new File("C:\\Users\\Favour's Computer\\workspace\\Physics Calculator\\src\\res\\icon.jpg");
I checked it online and i found out that the problem is that i got the file through the C:\\ directory, they said the image file should look like this :
File imageFile = new File("res/icon.jpg");
I tried this but it didnt work, I kept getting an error message like : file not found
This is my full code :
BufferedImage image = null;
try {
File imageFile = new File("C:\\Users\\Favour's Computer\\workspace\\Physics Calculator\\src\\res\\icon.jpg");
image = ImageIO.read(imageFile);
} catch(IOException e) {
e.printStackTrace();
}
setIconImage(image);
Please, i have been trying to solve this for weeks, do anyone know how i can solve this, please if you do, please help
The images should not be loaded from the file system, but should be bundled into the app, inside your jar.
If you put the image foo.png inside the jar, under the package com.bar.resources for example, you simply need to use
InputStream in = getClass().getResourceAsStream("/com/bar/resources/foo.png")
to load the image as an input stream.
That will use the class loader to load the image. So, during development, if you're using a standard IDE project, you just need to put the image file in the appropriate package in your source directory: the IDE will "compile" the file by copying it to the same directory as the generated .class files.
If you're using a standard Maven/Gradle project, then it needs to be put in the appropriate package under src/main/resources.
Problem is you dont have res folder in your project, first of create a folder a "res" by Right Clicking on project and place the image icon.jpg image in that "res". and
use : `File imageFile = new File("res/icon.jpg");`// To retrieve image to your project.
You cannot retrieve the image from your local system, because it is not attached with your projects workspace.
There are two options....
1)Either make res a "source folder" . You will know this if you are using Eclipse.
Then you can use like
ImageIO.read(new File("res/icon.jpg"));
2) If res is a normal folder, you will have to use. In this case res will be considered as a package
ImageIO.read(new File("src/res/icon.jpg"));

Categories

Resources