Loading resources like images while running project distributed as JAR archive
First of all, change this line :
image = ImageIO.read(getClass().getClassLoader().getResource("resources/icon.gif"));
to this :
image = ImageIO.read(getClass().getResource("/resources/icon.gif"));
More info, on as to where lies the difference between the two approaches, can be found on this thread - Different ways of loading a Resource
For Eclipse:
- How to add Images to your Resource Folder in the Project
For NetBeans:
- Handling Images in a Java GUI Application
- How to add Images to the Project
For IntelliJ IDEA:
- Right-Click the src Folder of the Project. Select New -> Package
- Under New Package Dialog, type name of the package, say resources. Click OK
- Right Click resources package. Select New -> Package
- Under New Package Dialog, type name of the package, say images. Click OK
- Now select the image that you want to add to the project, copy it. Right click resources.images package, inside the IDE, and select Paste
Use the last link to check how to access this file now in Java code. Though for this example, one would be using
getClass().getResource("/resources/images/myImage.imageExtension");
Press Shift + F10, to make and run the project. The resources and images folders, will be created automatically inside the out folder.
If you are doing it manually :
- How to add Images to your Project
- How to Use Icons
- A Little extra clarification, as given in this answer's first
code example.
QUICK REFERENCE CODE EXAMPLE(though for more detail consider, A little extra clarification link):
package swingtest;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
/**
* Created with IntelliJ IDEA.
* User: Gagandeep Bali
* Date: 7/1/14
* Time: 9:44 AM
* To change this template use File | Settings | File Templates.
*/
public class ImageExample {
private MyPanel contentPane;
private void displayGUI() {
JFrame frame = new JFrame("Image Example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
contentPane = new MyPanel();
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private class MyPanel extends JPanel {
private BufferedImage image;
public MyPanel() {
try {
image = ImageIO.read(MyPanel.class.getResource("/resources/images/planetbackground.jpg"));
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
@Override
public Dimension getPreferredSize() {
return image == null ? new Dimension(400, 300): new Dimension(image.getWidth(), image.getHeight());
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, this);
}
}
public static void main(String[] args) {
Runnable runnable = new Runnable() {
@Override
public void run() {
new ImageExample().displayGUI();
}
};
EventQueue.invokeLater(runnable);
}
}
Swing - Include images in JAR file
You are accessing your file through its path on disk before it gets put into a JAR. You need to use a resource loader as explained in:
How to read a file from jar in Java?
Java Images not drawn when running java -jar
Before all be sure your resource is correctly loaded (for example with a System.out())!
Instead to use ImageIcon(String location)
use ImageIcon(URL location)
constructor because your image is not on hdd, but live compressed as URL in your classpath (something like MyJar.jar!/path/to/image.png"); you have to modify your image loading as
this.getClass().getClassLoader().getResource("MyImage.png");
Image won't show up when using 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
Cannot Load Images from Jar
Check classpath of your project in your IDE. For example in eclipse there is configuration for each folder (Properties->JAva Build Path->Source Tab). It may be set to exclude png files.
How to includes all images in jar file using eclipse
You need to get it from the classpath instead of from the local disk file system.
Assuming that images
is actually a package and that this package is inside the same JAR as the current class, then do so:
final public ImageIcon iReport =
new ImageIcon(getClass().getResource("/images/Report.png"));
NullPointerException when loading images in .jar-file
URL url = ClassLoader.getSystemResource(image);
This URL translates to absolute path in the file system which will be an invalid path for a file within jar. For example, if you have a file called foo.png under bar.jar the URL will be /path_to_current_dir/bar.jar/!foo.png which is invalid. Instead you can read the file as a stream:
InputStream is = getClass().getClassLoader().getResourceAsStream(image);
ImageIO.read(is);
Write an image from project resources to the byte array
I suggest do the following:
Use commons IO, then:
InputStream is = getClass().getResourceAsStream("/icons/default_image.png")
byte[] bytes = IOUtils.toByteArray(is);
(try
and catch
the exceptions.)
Edit As of Java 9 no Library needed:
InputStream is = getClass().getResourceAsStream("/icons/default_image.png")
byte[] bytes = is.readAllBytes();
(Again try
and catch
the exceptions.)
Related Topics
How to Create a Generic Array in Java
Difference Between == and Equals() in Java
When to Use Linkedlist Over Arraylist in Java
Gui Not Working After Rewriting to MVC
How to Use Java.Util.Scanner to Correctly Read User Input from System.In and Act on It
How to Convert My Java Program to an .Exe File
How to Test a Class That Has Private Methods, Fields or Inner Classes
Connect to Kafka Running in Docker
Reading a Plain Text File in Java
Understanding Checked VS Unchecked Exceptions in Java
Loading Resources Like Images While Running Project Distributed as Jar Archive
Change Date Format in a Java String
Avoiding Nullpointerexception in Java
Show Jdbc Resultset in HTML in Jsp Page Using MVC and Dao Pattern
Solving a "Communications Link Failure" With Jdbc and MySQL
Official Reasons For "Software Caused Connection Abort: Socket Write Error"