I'm trying to set an icon for my Java app, with the image being in assets/images.
Setting it as so:
java.net.URL url = ClassLoader.getSystemResource("assets/images/ravens.jpg");
Toolkit kit = Toolkit.getDefaultToolkit();
Image img = kit.createImage(url);
frame.setIconImage(img);
Error I'm receiving:
Uncaught error fetching image:
java.lang.NullPointerException
at sun.awt.image.URLImageSource.getConnection(URLImageSource.java:115)
at sun.awt.image.URLImageSource.getDecoder(URLImageSource.java:125)
at sun.awt.image.InputStreamImageSource.doFetch(InputStreamImageSource.java:263)
at sun.awt.image.ImageFetcher.fetchloop(ImageFetcher.java:205)
at sun.awt.image.ImageFetcher.run(ImageFetcher.java:169)
Any help would be appreciated!
There is a better way to do this without getting a NullPointerException by using a BufferedImage. I've tested this and it works. Replace your code with this:
BufferedImage img = null;
try {
img = ImageIO.read(new File("assets/images/ravens.jpg"));
} catch (IOException e) {}
frame.setIconImage(img);
Given what you've stated in your comments, your assets directory is at the same level as src, so something like
/project
/src
/assets
What you need to do to make this
java.net.URL url = ClassLoader.getSystemResource("assets/images/ravens.jpg");
work is to have assets/images/ravens.jpg be on the classpath.
Eclipse puts anything inside a source folder on the root of the classpath when running your app.
Therefore, create a folder resources (or whatever you want to call it), make it a source folder, and put assets in it. It should look like
/project
/src
/resources
/assets
/...
Now, assets will be at the root of the classpath and you can retrieve it with the code above.
Use:
setIconImage(new ImageIcon("assets/images/ravens.jpg").getImage());
Related
I have a problem when exporting my java project. It cannot find the path of my image.
File Project
src
config
image
copy.png
This is where my image is located
String image1 = "image/copy.png";
shell.setImage(new Image(display, image1));
It works before i export but when i export it and update my program it gives me an error. I tried also to use InputStream but it gives me null.
With the specified class, org.eclipse.swt.graphics.Image, you will want to create the Image with method Image(Device device, InputStream stream) and use getClass().getResourceAsStream( image1 ) to supply the inputStream containing the file. You probably need "/" at the start of your path.
Create image with this method work well.
new Image(device, getClass().getResourceAsStream(localImagePath));
I have a problem to export my Jframe app with the background resource into jar file (without any external resource folder. I prefer to have everything into jar file for better portability).
Here's the code. On Eclipse all work correctly, but when I export into jar file the app doesn't load because the resource "cccc.jpg" is not found.
I have already tried the getResource() but it didn't work as well.
// Load Background image
BufferedImage img = null;
try {
img = ImageIO.read(new File("cccc.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
// Set Background image
Image dimg = img.getScaledInstance(640, 480, Image.SCALE_SMOOTH);
ImageIcon imageIcon = new ImageIcon(dimg);
setContentPane(new JLabel(imageIcon));
like
BufferedImage bufferedImage = ImageIO.read(MyClass.class.getResource("/images/cccc.jpg"));
see: Loading image from a resource Can't read input file
Saying that your code works in ecplise is a hint that you have located the "cccc.jpg" file in the root of your project folder (this is the current folder when you run the application or a unit test within eclipse).
For having the file packed as resource into your jar: simply put it somewher into your source folder. If you have your source packages named like "my.app.main" you could place your image file directly beside the your "my" folder and load it by:
InputStream is = ClassLoader.getSystemResourceAsStream( "cccc.jpg" )
Or place it into a sub package (e.g. "my.app.images") and load it by:
InputStream is = ClassLoader.getSystemResourceAsStream( "my/app/images/cccc.jpg" )
BTW: ImageIO.read can also take an InputStream as parameter.
I solved the problem. Now everything is loaded correctly when I open the jar file.
Link to the picture of the problem solved
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;
}
}
Alright, so I have created a Buffered Image to display on a JLabel. When I display the File location, it requires a src/ in front of the folder I want to access, or else an error will arise and I will not see the Buffered Image... I know that if I put the 'src/' in front of the resImg, the BufferedImage will not display outside of the IDE. Can anyone help?
This is the code that works inside of the IDE. When running outside from the .jar file, the image doesn't display.
static File f = new File("src/resImg/banner.png");
try {
banner = ImageIO.read(f);
picLabel = new JLabel(new ImageIcon(banner));
LabelPanel.add(picLabel);
} catch (IOException ex) {
Logger.getLogger(GameStart.class.getName()).log(Level.SEVERE, null, ex);
}
When the resource is in a jar file, it isn't a file on the local file system. You should use
URL imageSource = getClass().getResource("/resImg/banner.png");
if (imageSource == null) {
// Handle the resource being missing
}
picLabel = new JLabel(new ImageIcon(imageSource));
Here you're fetching the resources from the classloader, which will obviously have access to the files in your jar file.
If you want get image from jar, use smth like this:
URL imageurl = getClass().getResource("/images/imagename");
You cannot create a File object for a resource in the JAR file. Use this instead.
URL imgurl = this.getClass().getClassLoader().getResource("resImg/banner.png");
picLabel - new JLabel(new ImageIcon(imgurl));
Hope this helps.
You have to find a parent directory, the relativ path can start from like
workspace directory
directory the process starts
the relativ path is "realtiv" from where the java process is started from, so the path can change from time to time.
If the picture is placed in the jar, you can use
getClass().getResource("relativ jar path")
for finding the image. the jar itself knows, where it is placed.
Most probable cause is that your image is not packed inside jar file ( verify this with jar / zip tool ).
If image is there but does not display, it is because you trying to read this from file system relative to working directory ( and it is certainly not there )
So, proper solution would be to read image from class path:
Thread.currentThread().getContextClassloader().getResourceAsStream(... path to your image relative to jar root ---)
I have the following problem:
I created the servlet which should draw a dynamic graph. During the drawing process it should fetch the picture from another directory and to draw it upon another image. Everything should work fine:
try {
BufferedImage temp = ImageIO.read(new File("image/arrow.png"));
tempIm = temp.getScaledInstance(55, 55, Image.SCALE_SMOOTH);
} catch (IOException e) {
e.printStackTrace();
}
But it prints the following:
SEVERE: javax.imageio.IIOException: Can't read input file!
at javax.imageio.ImageIO.read(ImageIO.java:1275)
at CertificateDraw.doGet(CertificateDraw.java:36)
I tried to change the path of the File object in all possible ways it just gives the same problem even though the part of the image is still sent to the browser. So the problem is with the ImageIO.read part - how can I find why it does not load the image?!
I am working in Eclipse - servlet is in the src folder. The image is in "image" folder under the rot directory "WebContent".
Relative paths in java.io.File are relative to the current working directory (CWD). This is the folder which is currently opened when the command is given to start the Java runtime environment (in your case, the webserver). When starting the server in Eclipse, this is usually the /bin folder of the project. You can figure this by printing new File(".").getAbsolutePath().
But you shouldn't be relying on relative paths in File at all. The CWD is not controllable from inside the code.
As it's in the webcontent folder already, just get it by ServletContext#getResourceAsStream() instead.
InputStream input = getServletContext().getResourceAsStream("/image/arrow.png");
BufferedImage image = ImageIO.read(input);
// ...
Note that the getServletContext() is inherited from the GenericServlet class which the HttpServlet extends from, so you don't need to provide the method yourself.