GImage can't find my image - java

I was trying the acm library and when I tried to use the GImage it can't find my image. I tried putting it everywhere and still it can't find it. Where does GImage look for an image(please be specific) thank you

I was also having the same problem. I used the full-path and it worked, e.g.:
GImage img = new GImage("/Users/abc/java/programming/abc.jpg");
add(img);
Also, I just noticed that if you are using Eclipse, you can keep the image inside bin sub-directory and then you can use filename:
GImage img = new GImage("abc.jpg");
add(img);
For the above to work, your image should be at: /Users/abc/java/programming/bin/abc.jpg"

According to the docs. it specifically consists of the following steps:
Check to see if an image with that name has already been defined. If so, return that image.
Check to see if there is a resource available with that name whose contents can be read as an Image. If so, read the image from the resource file.
Load the image from a file with the specified name, relative to the application directory or the applet code base.

Related

Adding/Loading an image in java

I am trying to load an image to display on the screen (just to get an idea of how to do it).
The problem is that when the program tries to load "apple.png" (which is saved on my desktop), it cannot find the image - Where do image files need to be stored in order for them to be found? Here is my loading method:
private void loadImage() {
ImageIcon appleIcon = new ImageIcon("apple.png");
Image appleImage = appleIcon.getImage();
}
If you want to reach it from the desktop, you should use the complete path. The easiest way to handle resources would be to create a folder in you java project, which you can access via "folderName/fileName.example".
Using the full path is an option
C:\filefolder\file.jpg
To answer your question though
Wherever your java file is is where it's going to think "home is" make yourself a java workspace to put your java source files in and inside it create a folder to put any assets you want in that way you will simply be able to call "apple.jpg"
if you want use the file name only, the file path ("apple.png")is relative to the source folder. so you have to place it in there.
you could also use absolute the file path to your desktop (sthg like "C:\Users\your.name\Desktop")
From the javadoc:
Creates an ImageIcon from the specified file. The image will be preloaded by using MediaTracker to monitor the loading state of the image. The specified String can be a file name or a file path. When specifying a path, use the Internet-standard forward-slash ("/") as a separator. (The string is converted to an URL, so the forward-slash works on all systems.) For example, specify:
new ImageIcon("images/myImage.gif")
As #Shriram mentioned, when you only specify the filename (with extension), it will search for that file in the current directory.
Hint: There exists an constructor overload which takes an URL as argument.

How to set up Eclipse project to load an image so that it also runs from the command line

I've built a Java application that loads an image at runtime. The location of the image is fixed relative to the project.
I would like to be able to run the program from both within Eclipse and the command line and for it to load the image correctly. However, I can only do one or the other but not both. This seems like such a trivial thing to want to do but I can't find out how to do it.
The project is set up so that it creates a bin directory for the output and puts the image in a resources sub-folder. This is fine when running from the command line as I can write my code to look in that sub folder for the file.
But when I run the program from within eclipse the current working directory is different.
What am I missing?
TIA
Update - adding some code
This is what I had originally:
BufferedImage awtImage = ImageIO.read(new File(System.getProperty("user.dir") + "/resources/image-name.png"));
Following the advice in the comments I am trying to use getResourceAsStream but I don't know what to pass to the File constructor.
InputStream temp = MyClass.class.getResourceAsStream("resources/image-name.png");
BufferedImage awtImage = ImageIO.read(new File(???));
The resource is being found because temp is not null.
I think there's 2 solutions.
1) you specify an absolute path
2) your image is in the classpath so you could load it via :
YouClass.class.getResourceAsStream("YourImg.png");
The working directory, if that's really what you mean, is not a great place to load an image from. It appears that you have an image that you would distribute with your finished program so that the program could use it. In that case, I suggest that you use Class.getResourceAsStream(), and put the image in the directory with (or near) that class.
EDIT:
Here is code I used in one of my programs for a similar purpose:
ImageIcon expandedIcon = null;
// ...
expandedIcon = new ImageIcon(TreeIcon.class.getResource("images/Expanded.png"));
The ImageIcon class is part of Swing; I don't know if you're using that, but this should serve to show you the idea. The getResource() method takes a URL; again, you might need something a little different. But this shows the pathname relative to the path of the class on which the method is called, so if TreeIcon is in x/y/z/icons, the PNG file needs to be in x/y/z/icons/images, wherever that is on that computer.
TreeIcon is a class of mine, and its internals will not help you, so I'm not posting them. All it's doing here is providing a location for the PNG file I'm loading into an ImageIcon instance.
In addition to working on a disk with a directory structure, this also works in a jar file (which is a common way to distribute a java program or library). The jar file is just a zip file, and each file in the jar/zip file has its directory associated with it, so the image can be in the jar in the correct directory just as the java classes are in their directories.
getResourceAsStream() returns a stream; if you want to use that byte stream to load as an image, find a class that converts an stream to something your image class can use as a constructor or in a load method and hook them up. This is a common thing to have to figure out with Java i/o, unfortunately there is no cookbook way to do it across all images and situations, so we can't just tell you what it is.
EDIT 2:
As from the comment, try:
ImageIO.read(new File(MyClass.class.getResource("resources/image-name.png");
I set up my Eclipse projects like this.
The input directory is added to the classpath (JavaBuildPath in Eclipse).
Finally, you access the image and / or text files like this.
private BufferedImage getIconImage() {
try {
return ImageIO.read(getClass().getResourceAsStream(
"/StockMarket.png"));
} catch (IOException e) {
e.printStackTrace();
return null;
}
}

Java applet not able to find resource image with ImageIcon unless entire path is used

I've placed the image TestIcon.png in the src folder of a Java applet (the directory is C:\Users\User\workspace\applettest2\src\TestIcon.png). Everything I've read says that I should be able to use the image simply by referencing "TestIcon.png". Example:
ImageIcon xIcon = new ImageIcon("TestIcon.png");
Howerver, running the applet in Eclipse with this code doesn't work; the image is not displayed. If I type out the image's entire path:
ImageIcon xIcon = new ImageIcon("C:\\Users\\User\\workspace\\applettest2\\src\\TestIcon.png");
then the applet displays the image properly. Isn't the default path for resources supposed to be in the "src" folder? Thanks.
If you are running it inside the Applet then try with Applet#getCodeBase() and Applet#getDocumentBase
Image image = getImage(getDocumentBase(), "TestIcon.png");
Find more samples Here and Here

Java swing Image always has height and width of -1

I know that the method returns -1 when it couldn't get the width or height of the image, but I hope you can tell me why it can't manage to do that. Here I create a few ImageIcons and save them in an Image Array:
for(int x = 0; x < playerSprites.length; x++){
playerSprites [x] = new ImageIcon("player" + x + ".png").getImage()
}
Later I create an instance of the class which only creates this Array at the moment. When I then want to get the images from the Array in the other class I check their height and width and I always get -1 on both:
public Image nextImage(String name){
Image image = null;
if(name.equals("player")){
if(counter == animationImageManager.getPlayerSprites().length-1){
counter = 0;
}
image = animationImageManager.getPlayerSprites()[counter];
counter++;
}
return image;
}
If image is not found then still it return -1 for height and width.
Try below sample code to reproduce the issue:
System.out.println(new ImageIcon("").getImage().getWidth(null)); // print -1
It's worth reading Java Tutorial on Loading Images Using getResource
May be it's not loading the images properly.
You can try any one based on image location.
// Read from same package
ImageIO.read(getClass().getResourceAsStream("c.png"));
// Read from images folder parallel to src in your project
ImageIO.read(new File("images/c.jpg"));
// Read from src/images folder
ImageIO.read(getClass().getResource("/images/c.png"))
// Read from src/images folder
ImageIO.read(getClass().getResourceAsStream("/images/c.png"))
Read more...
The width/height for Image will return -1 if the image is null. When there's no image.
Suggestions:
use ImageIO.read() which will throw an IOException if something goes wrong with the IO, like the path being wrong.
If the image is a resource for your application, then don't read it as a file, read it as a resource via URL. For instance, if the image is in src/images, then you could do
URL url = getClass().getResource("/images/myimage/png");
BufferedImage image = ImageIO.read(url);
Important thing to note with ImageIcon is when you pass a String to the constructor, it will look for the file in the local file system. It may work when you are developing, but once you deploy the application with the images in the jar, it won't work anymore, with the file path, because it will no longer be valid. You could pass the URL to ImageIcon just the same as above, but like I said, ImageIO allows for more error detection.
Just so you understand what's going on in your current code, by you specifying just the image file name as the path to the ImageIcon, the search will look for the image in the root of the project folder (if you're working in an IDE) because that's the working directory. So if your images aren't there, the images won't be found.
Another thing to note about my second bullet point is how the image is search for. You can see the path I used "/images/myimage/png". What the / in the front does, is bring the search to root of the classpath, which in development view, is the src. The calling class will normally be in some package on the classpath, say com.hello.somepackage.SomeClass. So if SomeClass tries to call the getclass getresource without the /, the search will begin from the location of the class, which is in the package.
The are just some things to consider when using resources/images. But the first couple points should get you going.

How do I access a .gif file in a package in the src folder?

I'm working on a Java program using Eclipse. Right now, I have an src folder that contains 2 packages: memory.views and memory.resources.
In the memory.views package, I have my Main.java file. In the memory.resources package, I have my .txt file and .gif file.
Within the program, I have no problem accessing (and manipulating) the .txt file by using the path /memory/resources/name.txt. However, when I do the same with the .gif file using the code below, I get no result:
ImageIcon icon = new ImageIcon("/memory/resources/name.gif");
There's no error produced. The only effect is that I see no image when the program is running.
I've tried also writing the following, but none worked:
ImageIcon icon = new ImageIcon("/resources/name.gif"); <br>
ImageIcon icon = new ImageIcon("name.gif");
Now, just so nobody says that it's the .gif file's fault, I've actually entered in the full Finder path (I'm using a Mac) and that worked perfectly:
ImageIcon icon = new ImageIcon("/Users/[...]/src/memory/resources/name.gif");
However, I don't want to do the full path, because if I export the program and run it on another computer, then the non-programming computer won't display the image either.
So, right now, I don't even know what the problem is. The .gif file works sometimes, but not when it's accessed via the same path as the .txt file, which works all the time. I tried looking here (Cannot access resource by using the getResources() method), but it seems like he had a slightly different problem from me.
You can use
URL url = ClassLoader.getSystemResource("name.gif");
ImageIcon icon = new ImageIcon(url);
provided that your name.gif file ends up in classpath after compilation/build.
What is this ImageIcon class? Is it your own code?
Try Thread.currentThread().getContextClassLoader().getResourceAsStream("/memory/resources/name.gif");
See if this works...
File file = new File("/memory/resources/name.gif");
ImageIcon icon = new ImageIcon(file.getAbsolutePath());

Categories