This question already has answers here:
Load image from jar and outside it in eclipse
(2 answers)
Closed 6 years ago.
I exported a runnable jar file from the Eclipse IDE. In Eclipse the program works fine, but when exported the program refuses to open. To clarify, the images are in a source folder and loaded via URL through a resource loader class. I used JD-GUI to show the contents of my jar file and the images are packaged properly into the file (Picture of this included). Why is the jar file not running properly?
The problem
Here is my code for the URL Loader
public class MainPanel extends JPanel{
BufferedImage img1, img2;
URL url1 = ResourceLoader.class.getResource("1.jpg");
URL url2 = ResourceLoader.class.getResource("2.jpg");
MainPanel(){
try {
img1 = ImageIO.read(url1);
img2 = ImageIO.read(url2);
} catch (IOException e) {
e.printStackTrace();
}
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawImage(img1, 1, 0, null);
g.drawImage(img2, img1.getWidth(), 0, null);
if(g instanceof Graphics2D){
Graphics2D g2d = (Graphics2D)g;
}
}
}
Here is the resource loader class
final public class ResourceLoader {
public static InputStream load(String path){
InputStream input = ResourceLoader.class.getResourceAsStream(path);
if (input == null) {
input = ResourceLoader.class.getResourceAsStream("/"+path);
}
return input;
}
}
Edit:://
Here is the command prompt read-out for the error that is happening
enter image description here
While exporting the jar select the class that contains main method in "Launch Configuration. It should work fine. If you still face problem then run jar from command line using "java -jar jarfilename" command to see the exact error message.
Related
This code throws a NullPointerException and I have no idea why.
try {
imageIcon = new ImageIcon(ImageIO.read(new File("res/Background.png")));
backgroundImage = imageIcon.getImage();
signIn = new MyButton("SignIn", ImageIO.read(new File("res/SignIn.png")), ImageIO.read(new File("res/SignInHover.png")));
signUp = new MyButton("SignUp", ImageIO.read(new File("res/SignUp.png")), ImageIO.read(new File("res/SignUpHover.png")));
back = new MyButton("Back", ImageIO.read(new File("res/Back.png")), ImageIO.read(new File("res/BackHover.png")));
exit = new MyButton("Exit", ImageIO.read(new File("res/Exit.png")), ImageIO.read(new File("res/ExitHover.png")));
} catch(IOException e) {
JOptionPane.showMessageDialog(null, "");
}
res/ is a source folder in the project root which contains all images used in this piece of code but I'm not able to get it to work. I've tried using getClass().getResource() (which works from inside Eclipse but not from a .jar file) and getClass().getResourceAsStream() (which throws an exception telling that the input stream is null) but to no avail.
P.S.: MyButton is a user-defined class which extends JButton and has a constructor MyButton(String, final BufferedImage, final BufferedImage).
After all I succeeded by just making images folder under my source(i.e. under res) folder. And using method
ImageIO.read(getClass().getResource("/images/SignIn.png"));
I'm having a weird problem in java. I want to create a runnable jar:
This is my only class:
public class Launcher {
public Launcher() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
String path = Launcher.class.getResource("/1.png").getFile();
File f = new File(path);
JOptionPane.showMessageDialog(null,Boolean.toString(f.exists()));
}
}
As you can see it just outputs if it can find the file or not. It works fine under eclipse (returns true). i've created a source folder resources with the image 1.png. (resource folder is added to source in build path)
As soon as I export the project to a runnable jar and launch it, it returns false.
I don't know why. Somebody has an idea?
Thanks in advance
edit: I followed example 2 to create the resources folder: Eclipse exported Runnable JAR not showing images
If you would like to load resources from your .jar file use getClass().getResource(). That returns a URL with correct path.
Image icon = ImageIO.read(getClass().getResource("imageĀ“s path"));
To access images in a jar, use Class.getResource().
I typically do something like this:
InputStream stream = MyClass.class.getResourceAsStream("Icon.png");
if(stream == null) {
throw new RuntimeException("Icon.png not found.");
}
try {
return ImageIO.read(stream);
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
stream.close();
} catch(IOException e) { }
}
Still you're understand, Kindly go through this link.
Eclipse exported Runnable JAR not showing images
Because the image is not separate file but packed inside the .jar.
Use the code to create the image from stream
InputStream is=Launcher.class.getResourceAsStream("/1.png");
Image img=ImageIO.read(is);
try to use this to get image
InputStream input = getClass().getResourceAsStream("/your image path in jar");
Two Simple steps:
1 - Add the folder ( where the image is ) to Build Path;
2 - Use this:
InputStream url = this.getClass().getResourceAsStream("/load04.gif");
myImageView.setImage(new Image(url));
When I run my program as a Java Application, everything works fine. However, when I run my program as a Java Applet, the images do not load, and I get this stack trace:
javax.imageio.IIOException: Can't read input file!
at javax.imageio.ImageIO.read(Unknown Source)
at com.asgoodasthis.squares.Tile.<init>(Tile.java:42)
at com.asgoodasthis.squares.Component.start(Component.java:80)
at sun.applet.AppletPanel.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
I have a directory named res in my project directory, and I am loading my images like this:
public static BufferedImage tileset_terrain;
public loadImage() {
try {
//loading our images
tileset_terrain = ImageIO.read(new File("res/tileset_terrain.png"));
} catch(IOException e1) {
e1.printStackTrace();
}
}
So how do I get the images to load when I run my program as an applet? I am using Eclipse IDE.
It's likely the image can't be accessed from its current context, remember, applets normally run in a very tight security sandbox which prevents them from accessing files on the local/client file system.
You either need to load the images from the server the applet is been loaded from (using getDocument/CodeBase or a relative URL), or based on your example, as embedded an resource, for example
tileset_terrain = ImageIO.read(getClass().getResource("/res/tileset_terrain.png"));
This assumes that the image is included within the Jar file under the /res directory.
If the image resides on the server from which the applet is been load, you could also use
try {
URL url = new URL(getCodeBase(), "res/tileset_terrain.png");
img = ImageIO.read(url);
} catch (IOException e) {
e.printStackTrace();
}
Take a look at Reading/Loading images and What Applets Can and Cannot Do for more details.
Since it's an Applet and that runs in the browser hence you have to use Applet#getCodeBase() and Applet#getDocumentBase
Image image = getImage(getDocumentBase(), "tileset_terrain.png");
Find more samples Here and Here
The code You are using can induce many exception.
Image = getImage(getCodeBase(), "res/tileset_terrain.png");//can beused in your code
You can try this code.
import java.awt.*;
import java.applet.*;
public class DisplayImage extends Applet {
Image picture;
public void init() {
picture = getImage(getDocumentBase(),"res/tileset_terrain.png");
}
public void paint(Graphics g) {
g.drawImage(picture, 30,30, this);
}
}
I've done a lot of reading around SO and Google links.
I have yet to figure out how to correctly add an image into an eclipse gui project is such a way that the system will recognize find it. I know there's some mumbojumbo about CLASSPATH but it probably shouldn't be this difficult to do.
Let me start by describing what I'm doing...(If someone could correct me, it'd be appreciated.)
Here is my method.
I add the image using the "import wizard" (right click, "import", "general", "file") into an "import directory" I called "/resources"
Eclipse automatically creates a folder called "resources" in the eclipse package explorer's tree view. Right under the entry for "Referenced Libraries".
Note, "resources" isn't under "Referenced Libraries", it's at the same level in the tree.
I then use the following code:
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream input = classLoader.getResourceAsStream("/resources/image.jpg");
Image logo = ImageIO.read(input);
And at this point, I run the test program and get this error:
Exception in thread "main" java.lang.IllegalArgumentException: input == null!
at javax.imageio.ImageIO.read(Unknown Source)
at Test.main(Test.java:17)
Thanks for any help in advance!
Place the image in a source folder, not a regular folder. That is: right-click on project -> New -> Source Folder. Place the image in that source folder. Then:
InputStream input = classLoader.getResourceAsStream("image.jpg");
Note that the path is omitted. That's because the image is directly in the root of the path. You can add folders under your source folder to break it down further if you like. Or you can put the image under your existing source folder (usually called src).
You can resave the image and literally find the src file of your project and add it to that when you save. For me I had to go to netbeans and found my project and when that comes up it had 3 files src was the last. Don't click on any of them just save your pic there. That should work. Now resizing it may be a different issue and one I'm working on now lol
If you still have problems with Eclipse finding your files, you might try the following:
Verify that the file exists according to the current execution environment by using the java.io.File class to get a canonical path format and verify that (a) the file exists and (b) what the canonical path is.
Verify the default working directory by printing the following in your main:
System.out.println("Working dir: " + System.getProperty("user.dir"));
For (1) above, I put the following debugging code around the specific file I was trying to access:
File imageFile = new File(source);
System.out.println("Canonical path of target image: " + imageFile.getCanonicalPath());
if (!imageFile.exists()) {
System.out.println("file " + imageFile + " does not exist");
}
image = ImageIO.read(imageFile);
For whatever reason, I ended up ignoring most of the other posts telling me to put the image files in "src" or some other variant, as I verified that the system was looking at the root of the Eclipse project directory hierarchy (e.g., $HOME/workspace/myProject).
Having the images in src/ (which is automatically copied to bin/) didn't do the trick on Eclipse Luna.
It is very simple to adding an image into project and view the image.
First create a folder into in your project which can contain any type of images.
Then Right click on Project ->>Go to Build Path ->> configure Build Path ->> add Class folder ->> choose your folder (which you just created for store the images) under the project name.
class Surface extends JPanel {
private BufferedImage slate;
private BufferedImage java;
private BufferedImage pane;
private TexturePaint slatetp;
private TexturePaint javatp;
private TexturePaint panetp;
public Surface() {
loadImages();
}
private void loadImages() {
try {
slate = ImageIO.read(new File("images\\slate.png"));
java = ImageIO.read(new File("images\\java.png"));
pane = ImageIO.read(new File("images\\pane.png"));
} catch (IOException ex) {
Logger.`enter code here`getLogger(Surface.class.getName()).log(
Level.SEVERE, null, ex);
}
}
private void doDrawing(Graphics g) {
Graphics2D g2d = (Graphics2D) g.create();
slatetp = new TexturePaint(slate, new Rectangle(0, 0, 90, 60));
javatp = new TexturePaint(java, new Rectangle(0, 0, 90, 60));
panetp = new TexturePaint(pane, new Rectangle(0, 0, 90, 60));
g2d.setPaint(slatetp);
g2d.fillRect(10, 15, 90, 60);
g2d.setPaint(javatp);
g2d.fillRect(130, 15, 90, 60);
g2d.setPaint(panetp);
g2d.fillRect(250, 15, 90, 60);
g2d.dispose();
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
doDrawing(g);
}
}
public class TexturesEx extends JFrame {
public TexturesEx() {
initUI();
}
private void initUI() {
add(new Surface());
setTitle("Textures");
setSize(360, 120);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
TexturesEx ex = new TexturesEx();
ex.setVisible(true);
}
});
}
}
If you are doing it in eclipse, there are a few quick notes that if you are hovering your mouse over a class in your script, it will show a focus dialogue that says hit f2 for focus.
for computer apps, use ImageIcon. and for the path say,
ImageIcon thisImage = new ImageIcon("images/youpic.png");
specify the folder( images) then seperate with / and add the name of the pic file.
I hope this is helpful. If someone else posted it, I didn't read through. So...yea.. thought reinforcement.
When I try to run an applet in applet viewer it is not able to find resources (Image).
I try to load resource like this:
String cb= this.getCodeBase().toString();
String imgPath = cb+"com/blah/Images/a.png";
System.out.println("imgPath:"+imgPath);
java.net.URL imgURL = Applet.class.getResource(path);
but when i run it in appet viewer path is like this:
imgPath:file:D:/Work/app/build/classes/com/blah/Images/a.png
though image is there in this path,
is prefix file: causing problem, how can i test this code?
Will this code work when deployed in server and codebase returns a server URL?
Is your applet supposed to load images after it is loaded? Or would you be better served bundling necessary image resources in the jar with your applet?
I work daily on an applet-based application with plenty of graphics in the GUI.
They are bundled in the jar-file.
This si what we do:
// get the class of an object instance - any object.
// We just defined an empty one, and did everything as static.
class EmptyClass{}
Class loadClass = new EmptyClass().getClass();
// load the image and put it directly into an ImageIcon if it suits you
ImageIcon ii = new ImageIcon(loadClass.getResource("/com/blah/Images/a.png"));
// and add the ImageIcon to your JComponent or JPanel in a JLabel
aComponent.add(new JLabel(ii));
Make sure your image is actuallly in the jar where you think it is.
Use:
jar -tf <archive_file_name>
... to get a listing.
Just use /com/blah/Images/a.png as the path. getResource() is clever enough to find it.
The context classloader should work with jars.
ClassLoader cl = Thread.getContextClassLoader();
ImageIcon icon = new ImageIcon(cl.getResource("something.png"), "description");
Try this code it's only 2 methods out of the class I use to load images but it works fine for loading when using an applet.
private URL getURL(String filename) {
URL url = null;
try
{
url = this.getClass().getResource("" + extention + filename); //extention isn't needed if you are loading from the jar file normally. but I have it for loading from files deeper within my jar file like say. gameAssets/Images/
}
//catch (MalformedURLException e) { e.printStackTrace(); }
catch (Exception e) { }
return url;
}
//observerwin in this case would be an applet. Simply have the class have something like this: Applet observerwin
public void load(String filename) {
Toolkit tk = Toolkit.getDefaultToolkit();
image = tk.getImage(getURL(filename));
while(getImage().getWidth(observerwin) <= 0){loaded = false;}
double x = observerwin.getSize().width/2 - width()/2;
double y = observerwin.getSize().height/2 - height()/2;
at = AffineTransform.getTranslateInstance(x, y);
loaded = true;
}
I can post the rest of the class I use if needed