This question already has answers here:
Including Images with an executable jar
(2 answers)
Closed 6 years ago.
I need to display an image in a JPanel, but this image needs to be in a relative folder (my res folder) in my project path, so that my program can work on any machine, and the images are always available. The code I have for this so far is:
try {
BufferedImage image = ImageIO.read(new File("res/circle.jpg"));
JLabel picLabel = new JLabel(new ImageIcon(image));
panel2.add(picLabel);
picLabel.setLocation(220, 180);
picLabel.setSize(100, 100);
} catch (IOException e1) {
e1.printStackTrace();
}
This code is reading the error "Can't read input file!" and I cant figure out what I'm doing wrong.
(my res folder is located in the src folder of the project)
Let's take an example. Here is a small directory structure
main
|---MyClass.java
|---myfile.png
So main is package. You will need a class to reference any resource. Here I am using MyClass.
public Image getImage() throws IOException{
return ImageIO.read(MyClass.class.getResource("myfile.png"));
}
You can use something called get current directory. This will get the folder path that the project is working off of.
You can use it like so:
System.getProperty("user.dir")
Just add the image to the correct folder and then add the path and you're golden.
Related
This question already has answers here:
Jar get image as resource
(3 answers)
Closed 2 years ago.
So I'm using an image for the chess pieces in this basic chess game I'm making.
When I run the program in Eclipse, it works perfectly fine as expected. But when I use Eclipse to export and then run that program, it gives the error java.imageio.IIOException: Can't read input file!
The image is stored in the source folder in a package names images.
I load the image using
BufferedImage image = null;
try {
image = ImageIO.read(new File("src/images/Chess_Pieces.png"));
} catch (IOException e) {
System.out.println(e);
}
I've tried locating the image to many different places and I've tried different ways of loading the image, none of them work and I have made sure that the image actually appears correctly in the exported JAR file.
Change it:
image = ImageIO.read(getClass().getResource("/images/Chess_Pieces.png"));
See :
Different ways of loading a file as an InputStream
Loading image resource
This question already exists:
Referencing Image within JAR [duplicate]
Closed 3 years ago.
I know this has been asked before but I can't get it to work after trying all variations.I have a small program that I'm wanting the launch frame to have an image displayed on it. I can achieve this by having the jar in the same folder as the image and referencing it, however when I try to reference within the jar file itself I keep getting error:
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException
The code I am using is this:
private void imagePanel() {
setLayout(new BorderLayout());
BufferedImage image;
try {
image = ImageIO.read(this.getClass().getResource("/src/ticketMaster/img/logo.png"));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
add(new JLabel(new ImageIcon(image)), BorderLayout.CENTER);
}
I'm not sure if the path is incorrect, I have made a img folder inside the package named img which contains the logo. I have tried all variations of it
/img/logo.png
/ticketMaster/img/logo.png
/src/ticketMaster/img/logo.png
I am not able to get the image to load like I would just referencing the image outside of the jar. I've used resourceasstream as well and not had any luck with that.
Any ideas here?
I dont know your folder or your package structure, but you can try to remove the first '/' for the path you given in the getRessource() method, it may be looking for a absulute path.
I'm sorry for asking such a beginner question, but I just can't get it to work and I can't find the answer anywere either.
I want to have an image inside my .jar file and load it. While that sounds simple, I was only able to load an image while running from inside the IDE but not anymore after making the .jar (Thanks to google I was able to get the .png inside the .jar). Here is what I tried:
BorderPane bpMain = new BorderPane();
String fs = File.separator;
Image imgManikin;
try {
imgManikin = new Image(
Main.class.getProtectionDomain().getCodeSource().getLocation().toURI().toString()+"\\manikin.png");
bpMain.setBottom(new Label(Main.class.getProtectionDomain().getCodeSource().getLocation().toURI().toString()+"\\manikin.png"));
} catch (URISyntaxException e) {
imgManikin = new Image(
Main.class.getProtectionDomain().getCodeSource().getLocation().getPath()+"\\manikin.png");
System.out.println(Main.class.getProtectionDomain().getCodeSource().getLocation().getPath()+"\\manikin.png");
bpMain.setBottom(new Label(Main.class.getProtectionDomain().getCodeSource().getLocation().getPath()+"\\manikin.png"));
}
//Image imgManikin = new Image("file:src\\manikin.png");
ImageView imgvBackground = new ImageView(imgManikin);
imgvBackground.setFitWidth(100);
imgvBackground.setPreserveRatio(true);
bpMain.setCenter(imgvBackground);
primaryStage.setTitle("Kagami");
primaryStage.setScene(new Scene(bpMain, 300, 275));
primaryStage.show();
Needlessly to say it didn't work. It is showing me the Label at the bottom with the path just as intended, but it seams like the path just isn't right. (I also tried using the File.seperator instead of \\ and even /, but I got the same result every time: It showes me the path but won't load the image.
I'm using Windows 7, the IDE is IntelliJ and I have the newest Java update.
If the jar file is on the classpath of your application and the image to be loaded is located at the root of the jar file, the image can be loaded easily by:
URL url = getClass().getResource("/manikin.png");
BufferedImage awtImg = ImageIO.read(url);
Image fxImg = SwingFXUtils.toFxImage(awtImg, new Image());
Image fxImgDirect = new Image(url.openStream());
While ImageIO returns a BufferedImage this can be converted to a fx Image using the SwingUtils. However the preferred way is to directly create a new Image instance using the InputStream from the URL.
See also Load image from a file inside a project folder. If done right it does not matter if it is loaded from a jar file or the local file system.
The Image::new(String) constructor is looking for a URL. It is possible to construct a URL for a resource in a jar file, but it's much easier to use ClassLoader::getResource or ClassLoader::getResourceAsStream to manage that for you.
Given the file structure:
src/
SO37054168/
GetResourceTest.java
example/
foo.txt
The following, packaged as a jar will output
package SO37054168;
public class GetResourceTest {
public static void main(String[] args) {
System.out.println(GetResourceTest.class.getClassLoader().getResource("example/foo.txt"));
System.out.println(GetResourceTest.class.getClassLoader().getResourceAsStream("example/foo.txt"));
}
}
jar:file:/home/jeffrey/Test.jar!/example/foo.txt
sun.net.www.protocol.jar.JarURLConnection$JarURLInputStream#7f31245a
Note how the URL for the resource is not the same as the URL you were trying to construct. The protocol is different, and you need to have the ! after the path to the jar file.
I'm trying to access some resources located in the top directory of my (Java) project (/resources/imgname.jpg) from a class 'GUI' located in a package 'gui'.
Originally I used the following code:
ImageIcon image = new ImageIcon("./resources/imgname.jpg");
Image img = image.getImage();
This works fine in Eclipse, but doesn't display the image when it's in a runnable JAR. So after some searching it seems you need:
InputStream resource = GUI.class.getResourceAsStream("./resources/imgname.jpg");
try {
Image image = ImageIO.read(resource);
} catch (IOException e) {//trycatch needed because of read method}
Now this doesn't work in either Eclipse or JAR.
I've tried changing reference and location, but the only way I can get the image to display is by placing it in the 'gui' package folder. So is there any way I can reference it in the top folder of the project instead (so I don't have to move the resources to 'gui')?
Thx,
Magic
Try this.
InputStream resource = GUI.class.getClassLoader().getResourceAsStream("resources/imgname.jpg");
It works for me.
I have a Java project with a toolbar, and the toolbar has icons on it. These icons are stored in a folder called resources/, so for example the path might be "resources/icon1.png". This folder is located in my src directory, so when it is compiled the folder is copied into bin/
I'm using the following code to access the resources.
protected AbstractButton makeToolbarButton(String imageName, String actionCommand, String toolTipText,
String altText, boolean toggleButton) {
String imgLocation = imageName;
InputStream imageStream = getClass().getResourceAsStream(imgLocation);
AbstractButton button;
if (toggleButton)
button = new JToggleButton();
else
button = new JButton();
button.setActionCommand(actionCommand);
button.setToolTipText(toolTipText);
button.addActionListener(listenerClass);
if (imageStream != null) { // image found
try {
byte abyte0[] = new byte[imageStream.available()];
imageStream.read(abyte0);
(button).setIcon(new ImageIcon(Toolkit.getDefaultToolkit().createImage(abyte0)));
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
imageStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} else { // no image found
(button).setText(altText);
System.err.println("Resource not found: " + imgLocation);
}
return button;
}
(imageName will be "resources/icon1.png" etc). This works fine when run in Eclipse. However, when I export a runnable JAR from Eclipse, the icons are not found.
I opened the JAR file and the resources folder is there. I've tried everything, moving the folder, altering the JAR file etc, but I cannot get the icons to show up.
Does anyone know what I'm doing wrong?
(As a side question, is there any file monitor that can work with JAR files? When path problems arise I usually just open FileMon to see what's going on, but it just shows up as accessing the JAR file in this case)
Thank you.
I see two problems with your code:
getClass().getResourceAsStream(imgLocation);
This assumes that the image file is in the same folder as the .class file of the class this code is from, not in a separate resources folder. Try this instead:
getClass().getClassLoader().getResourceAsStream("resources/"+imgLocation);
Another problem:
byte abyte0[] = new byte[imageStream.available()];
The method InputStream.available() does not return the total number of bytes in the stream! It returns the number of bytes available without blocking, which is often much less.
You have to write a loop to copy the bytes to a temporary ByteArrayOutputStream until the end of the stream is reached. Alternatively, use getResource() and the createImage() method that takes an URL parameter.
To load an image from a JAR resource use the following code:
Toolkit tk = Toolkit.getDefaultToolkit();
URL url = getClass().getResource("path/to/img.png");
Image img = tk.createImage(url);
tk.prepareImage(img, -1, -1, null);
The section from the Swing tutorial on How to Use Icons shows you how to create a URL and read the Icon in two statements.
For example in a NetBeans project, create a resources folder in the src folder. Put your images (jpg, ...) in there.
Whether you use ImageIO or Toolkit (including getResource), you must include a leading / in your path to the image file:
Image image = Toolkit.getDefaultToolkit().getImage(getClass().getResource("/resources/agfa_icon.jpg"));
setIconImage(image);
If this code is inside your JFrame class, the image is added to the frame as an icon in your title bar.