I know, I know, this has been asked before. But every resource I've looked at uses IconImages while I just have plain Images.
Is there a different solution? Please help as I've been stuck researching and trying to figure this out for days now with no progress.
Image Floor = Toolkit.getDefaultToolkit().getImage("Floor.PNG");
EDIT: If I was to make sure the jar wouldn't compress and I created a seperate directory in the jar for images and put the correct file path, would this code work?
Toolkit#getImage(String s) looks for a file and likely your image is in the Jar and is now a resource not a file. Look to using resources for this.
Note that ImageIO.read(...) can accept an InputStream parameter the Class class has a method, getResourceAsStream(...) which can put the resource into a Stream that ImageIO can read. Give that a try.
Also, are you getting any error messages when you try what you're doing?
Make sure you know what your current directory is, and how it relates to the position of the files in your jar.
Here's how I would handle it.
1) Require there to be a file called "images.txt" in the directory with your jar (or bundle it into the jar.)
2) Make a file called "images.txt" with a format like `FLOOR:C:\\images\\floor.png`
3) Load this file into memory on load.
4) Load your images based on the entries in the file
This will give you the advantage of changing your images without changing your code if it's defined outside the jar :)
It's not loading because you're not putting the path to the images in the declaration. It expects the images to be wherever the jar is (notice there's no directories there)
You need to offload the definition of the file names to a file, or at the very least guarantee the relative position of the files.
Another good option is to put the images in the jar itself, say in an img directory, and reference them there. But then changes to the images require a new jar, which may not be desired for development purposes.
The getImage call is looking in the file system working directory, not inside the Jar file. This is why the jar file loads the images successfully when they are placed in the same directory outside the jar file. If the images are bundled in the jar file, they are no longer file system files to be accessed, but rather Jar file resources. There is a different way to load these, but sorry, I don't know it off the top of my head.
Check the extension of files. I had this problem because the extension was "PNG", when I changed it to "png", everything was ok.
You can't expect a JAR file to magically know where your images are. If you put a JAR file alone on the desktop, it's going to look for the files on the desktop! The code
getImage("Floor.png")
searches the current directory of the JAR (or source project) by default and you'd expect that if the JAR was in the same directory, it would work. If the JAR is on the desktop how does it know where Floor.png is? Of course, you can specify a hard-coded path
getImage("C:\Some Folder Path\Floor.png")
but then Floor.png has to be in C:\Some Folder Path\ for the JAR to work properly.
It sounds like what you really want to do is keep the images in the JAR file (which acts like a ZIP file). The tutorial on doing that is here:
http://download.oracle.com/javase/tutorial/uiswing/components/icon.html#getresource
And I know for ImageIcon you use: new javax.swing.ImageIcon(getClass().getResource("myimage.jpeg") but I have not found anything similar for plain Image.
<head-desk /> You should really get into reading the JavaDocs. Otherwise you are 'coding by magic'. Which generally won't work.
URL urlToImage = getClass().getResource("myimage.jpeg");
// If you need to support Java 1.3
Image image = Toolkit.getDefaultToolKit().getImage(urlToImage);
// If your users have dragged their JRE into this millennium
BufferedImage bufferedImage = ImageIO.read(urlToImage);
Related
Possibly a duplicate, though I doubt so since I have not seen anything so far completely answering my criteria in a way that I can complete my program
Background
What I need is to access another jar, from a seperate jar, read and write files to that jar. So far what I have done is change the jar to a zip and then I can delete files, but the problem I am having is with writing files back in, specifically image files (.txt works perfectly fine)
Question
How do I write image files to a zip (that was originally a jar) from another java program (in the end product another jar)
Note
I have looked around and most sources say this is not possible, but those questions dealt with this during the running of a program, my special case is that the other program is not running, but in file format. All I want to do is write and image in and convert it back to a jar and not have any problems with running that jar in the end.
Thank you!
Use FileSystems to access, write and replace the contents of the jar file:
try (FileSystem fs = FileSystems.newFileSystem(Paths.get("path/file.jar"), null)) {
Files.copy(Paths.get("path/to/image"), // path to an external image
fs.getPath("image.jpg"), // path inside a jar file
StandardCopyOption.REPLACE_EXISTING);
}
i have following line
File file = ResourceUtils.getFile("classpath:calculation.csv");
and i also tried
File file = ResourceUtils.getFile("classpath:/calculation.csv");
but both will throw an error
java.io.FileNotFoundException: class path resource [calculation.csv] cannot be resolved to absolute file path because it does not exist
but i do have calculation.csv in by resources folder..
why is this?
I need to read file from resources folder, and it should also work in server enviroment
EDIT:
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("calculation.csv").getFile());
works just as fine, so not at all..
EDIT2:
tried with folder.. i have both calculation.csv and csv/calculation.csv in my resources folder now..
none of the above work, with /csv/ added.
what kind of path does this thing want?!
EDIT3:
aaand
File file = new ClassPathResource("calculation.csv").getFile();
is also no go, what even is this..
Loading file (as FILE) wont work. You must use it as resource. Files inside JAR will not work as file anyway. This is also what your "check" code shows.
classLoader.getResource("calculation.csv") works, because you are using classloader to get resource, not filesystem to get file (which is what File api does). It could work, if you would deal with non packed application. Once you pack your app into JAR, file path will be like your/path/to/jar.jar!someResource - note ! mark (and that is what you would see as well). So basicly it will return File instance, you that you wont be able to use anyway, as file system has no access to it.
You could alternatively try to extract it first with ResourceUtiuls#extractJarFileURL(URL jarUrl) and then use extracted file.
I think, that in most cases Class#getResourceAsStream is the way to go and I think that it should fit your needs as well to read content of resource.
We are programming a game, which shall be startable from a .jar file. First we created a Project in IntelliJ and loaded the Images from a ZIP with the following code:
ZipFile zf = null;
try {
zf = new ZipFile(zipPath);
Image Image = ImageIO.read(zf.getInputStream(zf.getEntry("Block/Air.png")));
} catch (IOException ignored) {}
Now the attempt without the ZIP (just from the .jar) is:
Image image=ImageIO.read(getClass().getResourceAsStream(path+ "Block/Air.png"));
It doesn't load any texture. Do you have a better way to do this in combination?
Edit:Seems not to be the Problem.
Since jars are zip files you could place them in the jar file and placing them the classpath.
Image image=ImageIO.read(getClass().getResourceAsStream(path+ "Block/Air.png");
Path must be a relative path from a source path root. E.g. I have a file in "src/main/resource/my/cool/game/" path is "/my/cool/game".
If you want to use a zip file, it must be outside of your jar file. To load the zip, you could use a relative file path, which is the same if you start your game from Intellij and from dekstop.
To change the working directory in intellij look here.
The best way would be to place the zip file alongside the jar so you can use "." as working directory to load the zip file.
Alternatively you could use a fixed directory, but then your game needs some sort of installation so it knows where to finde the zip file.
If you use ".", the zip file needs to be in the root of the project directory.
The Class.getResource and Class.getResourceAsStream methods take a URL (not a file path!) which is relative to the root of each classpath entry. For classpath entries which are .jar files, this means the path of a file packaged within the respective .jar file.
If your entire program is in one .jar file, the classpath consists of just one item: that .jar file. Therefore, there is only one classpath root, and the String you pass to getResourceAsStream is the URL of an entry within your .jar file. Do not include the path to the .jar file in that String.
If you are not sure what you should pass, examine your .jar file's contents. Every IDE (that I know of) provides a way to do this. You can also use any unzip utility to examine a .jar file, since every .jar file is actually a .zip file. (If you only have Windows, with no zip tools installed, make a copy of the .jar file and change the copy's extension to ".zip", then open it.)
Inside the .jar file are, of course, zip entries. The full path of the entry you want to load (without the path to the .jar file) is what you must pass to getResourceAsStream. getResourceAsStream accepts a URL, and URLs always use forward slashes (/) on all platforms, so do not use any backslashes. Also, the first character of the String must be /.
It is actually possible to specify a shorter path, depending on how your images are packaged in the .jar, but that is a separate topic. See the documentation for full details.
Side note: Never, ever write an empty catch block. Ever. That caught exception is by far the easiest way for you or anyone else to know when and why your program is not working. At the very least, put exc.printStackTrace(); in your catch block. More often, the correct course of action is to abort the program with something like throw new RuntimeException(exc);. After all, your program can't continue to function properly if it can't load that image, right?
Why do you need to store your images in a zip file? If you're doing it to reduce the file size, you gain absolutely nothing from zipping it first. JAR files are zipped files anyway (if you don't believe me, rename your .jar file to .zip, and try to open it). What you're basically doing is attempting to zip an already zipped file, which doesn't really do anything.
I would recommend you unzip your images and store them somewhere like < resources >/images
If you insist on leaving them zipped, you'll need to change it to something like this. Otherwise, it's looking for the zip file in the working directory (directory from which the jar was executed)
ZipFile zf = new ZipFile(getClass().getResourcesAsStream("path/to/zip"));
Disclaimer: I am not familiar with the ZipFile class, so I do not know if that constructor exists.
I am attempting to load an image called Default.png stored within the project and draw it onto a canvas. I am well aware of ImageIO.read however no matter what path I give it, I can't seem to load it. Where should I put the image? I have tried putting it in a separate folder calles "res," putting it into assets.author.mypackagename.textures, but no matter what I do I cannot seem to find the right location and how to access it. Any help is appreciated, comment for further specifics.
Actually the resources are loaded in the classpath relative to the current package. If /com/daniel/project/src/ is in your classpath, and images are in /com/daniel/project/src/image then use:
ImageIO.read( ClassLoader.getSystemResource( "image/Default.png" ) );
But the src folder is not included in the classpath by IDEs generally. Try adding the image to the bin folder.
If You have it in a separate folder called res you can load the image by doing this:
ImageIO.read(this.getClass().getResource("/Default.png"));
you can also do something like:
ImageIO.read(new File("res/Default.png"));
The second method doesn't need the picture to be in another folder, but for me it's cleaner that way.
I want to set icon to my JFrame. I do the following:
Image icon = Toolkit.getDefaultToolkit().getImage("src/images/icon.jpg");
this.setIconImage(icon);
It works fine when I run this code from netbeans, but when I try to run this code from jar file, images are not shown in my JFrame. I have tried to load images as resources:
this.setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("/src/images/icon.jpg")));
but when I run this code it fails with NullPointerException
Uncaught error fetching image:
java.lang.NullPointerException
at sun.awt.image.URLImageSource.getConnection(URLImageSource.java:99)
at sun.awt.image.URLImageSource.getDecoder(URLImageSource.java:113)
at sun.awt.image.InputStreamImageSource.doFetch(InputStreamImageSource.java:240)
at sun.awt.image.ImageFetcher.fetchloop(ImageFetcher.java:172)
at sun.awt.image.ImageFetcher.run(ImageFetcher.java:136)
How can I do this work?
edit:
Thanks to all,
the problem was solved by specifying image as
Toolkit.getDefaultToolkit().getImage(getClass().getClassLoader().getResource("images/icon.JPG"))
As for it seems rather weird, and would be better if it was like
this.setIconImage(new ImageIcon(pathToIcon).getImage());
Assuming your JAR file has a top level directory called images, you can use either:
getClass().getResource("/images/icon.jpg") or
getClass().getClassLoader().getResource("images/icon.jpg")
Looking at the source code of URLImageSource, it appears that the reason that getConnection throws an NPE is that it has a null for the url. And that leads me to suspect that
getClass().getResource("/src/images/icon.jpg")
is returning null. It would do that if it could not locate a resource with that pathname.
I bet that the problem is that you've got the path wrong.
To prove / disprove this, you should run jar tvf on the JAR file, and look for the line that matches "icon.jpg". Is the corresponding pathname the same as what you are using? If not, use the pathname from the matching line in the getResource call and it should work. Alternatively, if the file doesn't show up at all, look at the NetBeans build configs that tell it what to put in the JAR file. (I'm not a NetBeans user, so I can't say where you would need to look ...)
If that leads you absolutely nowhere, another possibility is that getClass().getResource(...) is using a classloader that doesn't know about the JAR file containing the image. (This seems pretty improbable to me ...)
getResource() loads a resource from classpath, not an OS path, and the after compilation your classpath will not include the /src folder, but rather just its contents. So you'd better try /images/icon.jpg.
Also you may find this discussion somewhat useful.
This should do it assuming you can import javax.imageio.ImageIO:
Image icon = ImageIO.read(this.getClass().getResource("/src/images/icon.jpg"));
this.setIconImage(icon);
.."/src/images/icon.jpg"..
The '/src' prefix of the address seems suspicious. Many apps. will provide separate 'src' and 'build' directories, but it normally ends up that the 'src' prefix is not used in the resulting Jar. I recommend trying..
.."/images/icon.jpg"..
& also triple checking that the image is in the location of the Jar that the code is expecting to find it.
For this to work, you should access the images from a directory relative to some fixed class.
For example, if the image files are saved in a directory "images" on the same level as the Toolkit.class, then
this.setIconImage(Toolkit.getDefaultToolkit().getImage(Toolkit.class.getResource("images/icon.jpg")));
should work.
You can simply create a package inside the main source, and incluse your images in this package. Then, just call the images in your main class like:
ImageIcon a = new ImageIcon(MainClass.class.getResource("/Package/Image.jpg"));
JFrame f = new JFrame("Edit Configure File");
//Image image = ImageIO.read(getClass().getResource("images/ctx.Icon"));
f.setIconImage(new ImageIcon("images/ctx.PNG").getImage());//this works for me finally
//f.setIconImage(image);
//f.setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("images/ctx.PNG")));