load an image from project's folder in java - java

I want to load an image which is in my projet folder as : /src/images/URL.jpg
I tried this code :
BufferedImage image = ImageIO.read(getClass().getResource("/images/URL.jpg"));
But I'm getting this error :
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: input == null!
at javax.imageio.ImageIO.read(ImageIO.java:1388)
at Personel.PersonnelMainForm.print(PersonnelMainForm.java:464)
How can I solve this problem ?

From personal experience I use:
BufferedImage image = ImageIO.read(getClass().getResourceAsStream("/images/image.jpg"));
I get the resource as a stream and that seems to work fine for me.

You can try this version of read, which takes File as an argument.
BufferedImage image = ImageIO.read(new File("path"));
where path is the path to you file, absolute or relative as you need.
Another option, if you really want to load it as a resource, would be editing your classpath, as per this question.

I suppose you have a java class in the package.
You have to move up so many times as package levels.
Example:
Java class is defined as org.test.MyClass
you have to go up twice (../../) to be in the main directory.

Related

Why getClass().getResourceAsStream(file.getAbsolutePath()) throws nullPointerException?

After I've searched for a solution for my problem & reading similar questions which are very more professional than mine,... well, I hope you pay attention to my problem, even though it seems simple!
I'm working on a project which open files by FileChooser, then I'm trying to show it on a pane. The problem is getClass().getResourceAsStream(file.getAbsolutePath()) returns null.So while I can print the path & see it's true, but I cannot use it in creating images. Part of my code is:
FileChooser fileChooser = new FileChooser();
File file = fileChooser.showOpenDialog(stage);
...
Image img = new Image(getClass().getResourceAsStream(file.getAbsolutePath());
The exception is:
Exception in thread "JavaFX Application Thread" java.lang.NullPointerException: Input stream must not be null ...
I work on Ubuntu by NetBeans.
I really appretiate helps. Thanks.
Use ImageIO:
Image img = ImageIO.read(file);
getResourceAsStream requires a path on the class path. As the resource could be in a jar, its full URI would be jar:file:/..../xyz.jar!/.... And File is on the file system.
One cannot mix those, only Path is a new generalisation allowing paths in several "file" systems.

problems getting pictures inside a Jar with :CImgPanel imgPanel = new CImgPanel

Hey I got a problem with getting all my pictures inside a JAR file
This is the code that is bothering me
CImgPanel imgPanel = new CImgPanel(new ImageIcon("img/logo1.png").getImage());
i have tried getClass().getResource and this.getClass().getClassLoader().getResourceAsStream
I have tried everything i could think of and i have look many place before asking here but no one got this problem,does anyone know what i can do to get the pictures inside the Jar?
Thanks in advance
I recommend:
Obtain your images using ImageIO.read(getClass().getResourceAsStream(IMAGE_PATH)) where the IMAGE_PATH is the path relative to the class files. This will return a BufferedImage.
Create your ImageIcon from the BufferedImage if an Icon is needed.
If this still doesn't work, show us the contents of your jar file by doing, jar tf MyJarFile.jar, and then print the results here as an edit to your original question. Also show your actual code attempt and any and all error messages that your code may generate.

Loading an image from the Resource Folder

The code I am using to load the image is:
ImageIO.read(SpriteSheet.class.getResource(path));
The path being the path to the resource. But it would error with IllegalArgumentException. I wondered what might be causing and came to the conclusion that the resource should be added into the same path as the class.
Is it possible to load the image from another folder, like a res folder outside of the bin folder? (folder holding compiled classes)
EDIT:
So i messed around with a few things, and came to a solution. But now I have another problem. Here is my code
File sheet = new File(SpriteSheet.class.getProtectionDomain().getCodeSource().getLocation().getPath());
URI uri = sheet.toURI();
BufferedImage image = ImageIO.read(uri.toURL());
When I try to run it, it gives me an IIOException: Can't read Input File
This means that I can never actually get it work. I tried debugging by prining the URL to the console and this is the URL.
C:\Users\Amma\Abhijeet\Eclipse%20Workspace1\Test%20Game\bin
The %20 comes in the middle. Meaning that the file is and never can be acceesed. Is there anyway I can fix this?
Thanks.
Class.getResource will return null if the resource could not be found or the invoker doesn't have adequate privileges to get the resource.
All variants of ImageIO.read will throw an IllegalArgumentException if they receive a null input.
Take a look at the documentation of the getResource to understand how an absolute resource name is constructed from the given resource named and what are the rules for searching resources.
You can read images from any location as long as you have permissions to do so, the ImageIO.read method accepts a File, URL or InputStream so you have many option to do it.

How to set icon image for swing application?

I've seen many different examples showing how to set a JFrame's IconImage so that the application uses that icon instead of the standard coffee mug. None of them are working for me.
Here's "my" code (heavily borrowed from other posts and the internet at large):
public class MyApp extends JFrame
{
public MyApp()
{
ImageIcon myAppImage = loadIcon("myimage.jpg");
if(myAppImage != null)
setIconImage(myAppImage.getImage());
}
private ImageIcon loadIcon(String strPath)
{
URL imgURL = getResource(strPath);
if(imgURL != null)
return new ImageIcon(imgURL);
else
return null;
}
}
This code fails down in loadIcon when making a call to the getResource() method. To me, there's only 2 possibilities here: (1) the myImage.jpg is in the wrong directory, or (2) getResource() doesn't like something about my image (I had to convert it from CMYK to RGB in Photoshop so I could use the same image elsewhere with ImageIO.)
I have used the System.out.println(new File(".").getAbsolutePath()); trick to locate the directory where the image JPG should be stored, and still nothing worked. I have subsequently placed the JPG in just about every directory inside my project, just to rule file location out as the culprit.
So that leaves me to believe there's something that getResource() doesn't like about the JPG itself. But I have now already exhausted my understanding of images and icons in the mighty, wide world of Swing.
My JPG loads fine in other image viewers, so that's ruled out as well. Anyone have any ideas?
Thanks in advance!
I have tried following which was a answer for same kind of question like yours. And it works for me.
Try putting your images in a separate folder outside of your src
folder. Then, use ImageIO to load your images. (answered Aug 27 '13 at 0:18
AndyTechGuy)
frame.setIconImage(ImageIO.read(new File("res/icon.png")));
put the image in the root of the classpath and say getResource("classpath:myimage.jpg");
The problem with your code is that jvm is unsure where to lookup the image file so its returning null.
Here is a nice link about classpath
It should be
if(imgURL != null)
^
instead of
if(imgURL !- null)
and
URL imgURL = this.getClass().getResource(strPath);
instead of
URL imgURL = getResource(strPath);
Then it works fine, if "myimage.jpg" is in the same dir with MyApp.class
Two suggestions:
Try using the getClass().getResource("x.jpg"), and putting the file directly in the same folder as the .class file of the class you are in.
Make sure the name is identical in case - some operating systems are case sensitive, and within a JAR, everything is case sensitive.
You can try to use a "/" before your filename.
getClass().getResource("/myimage.jpg")
If you look into your build-output folder (target) you can look for your class where you are trying to get your resource from.
Your resources will probably be copied in some folders above.
For example your target directory could look like this:
target
|- de.example.app
|- Main.class
|- Main-x.y.z.jar
|- myimage.jpg
So if you just go for getClass().getResource("myimage.jpg") it will look under the folder target/de/example/app and won't find a jpg there.
You need to tell him that you want to look under the root-folder (target/**). That's why you need to place a "/" before your file.

Java getClass().getResource("file") leads to NullPointerException

I am following the Snake Java games tutorial and always get this error:
ImageIcon iid = new ImageIcon(this.getClass().getResource("ball.png"));
ball = iid.getImage();
Exception in thread "main" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(Unknown Source)
at snake2.Board.<init>(Board.java:52)
at snake2.Snake.<init>(Snake.java:10)
at snake2.Snake.main(Snake.java:22)
I actually just copied and pasted the code to see how it works. They are in the right packages too; but when I try to run it, I always end up with this error.
The image should be in the same package (folder in OS terms) as the compiled class. Check whether you have both .class and .png in the same folder. If not, you can use classpath-relative paths in getResource(..), by starting with /
Try this:
ImageIcon iid = new ImageIcon(this.getClass()
.getClassLoader().getResource("ball.png"));
ball = iid.getImage();
Make sure image is in the same folder as java file.
Try using System.out.println(System.getProperty("java.class.path")); to find out location of your .class file and place the images in this folder.
It is general risky to load resources using relative paths, I'd always recommend using absolute paths, so do
/ball.png
if the the image is at the root of your classpath, or add a path to the location.
You have to put the image file(ball.png) into your classpath. More details, please take a look at the Javadoc.
if the resource is in your classpath then you should be trying "this.getClass().getClassLoader().getResource("ball.png")". For you actual code to work, the ball.png needs to be in the location where your .class file is (i.e., inside the package).
Go to project >clean in the eclipse it would refresh the package explorer and you won't face this problem anymore.
You may need to add the file to your build resources, something like this:
<build>
<resources>
<resource>
<directory>path\to\resources</directory>
<includes>
<include>ball.png</include>
</includes>
</resource>
</resources>
You can use only path of your image. I think this will help you:
Use this:
ImageIcon iid = new ImageIcon("C:\\Users\\ranig\\My\\spaceinvaders\\ball.png");
Note: C:\\Users\\ranig\\My\\spaceinvaders\\ball.png is the whole path of ball.png image.
instead of this:
ImageIcon iid = new ImageIcon(this.getClass().getResource("ball.png"));
Note: If u want to only try snake code and only want to get output.
I will make it simple for you . Here is an example:
Icon bug = new ImageIcon(getClass().getResource("bug1.png"));
here "bug1.png" is the resource and if it is unavailable then it can cause error as you have discussed here.
Import an image to the same directory in which your program resides.
You can also give whole path to it as well
ImageIcon(getClass().getResource("C://me/file/bug1.png"));
The resource so named wasn't found. It needs to be in the same directory as the .class file you are calling it from. See the Javadoc.

Categories

Resources