I am reading a 100 MB picture into my app. It works fine inside Eclipse, but not when I export project to a JAR. Then, I get "Can't read input file!"
Since I need to edit it, I used BufferedImage.
private String str = "images/1.png";
BufferedImage imageMap;
//in constructor
imageMap = ImageIO.read(new File(str));
I have tried this, but the project image does not load inside Eclipse:
imageMap = ImageIO.read(this.getClass().getClassLoader().getResource(str));
Check you working directory if the image is loaded from the file system. Then you see if your relative path "images/1.png" is valid. Or you directly check the path of your png
System.out.println(new File("."));
File f = new File("images/1.png");
System.out.println(f.getAbsolutePath());
Related
After using images for example on a Button, when I build the application creating the .jar file and execute only the file, the images are not there but would only show if I copy the images folder in the same directory as the jar file. Why is that and how can I resolve this if possible?
I am currently using the following code to set the icon/image:
JButton btn = new JButton("Text", "img/icon.png");
The fact that you can use the images when they are stored outside the jar, suggests that you are doing something of the kind:
File image = new File("directory/image.jpg");
InputStream is = new FileInputStream(image);
This reads a file from a directory on the file system, not from the classpath. Now, if you have packaged your image in a "directory" inside your Jar, you must load the image from the classpath.
InputStream is = getClass().getResourceAsStream("/directory/image.jpg");
(note the slash in the path)
Or
InputStream is = getClass().getClassLoader().getResourceAsStream("directory/image.jpg");
(note the absence of the slash in the path)
Your example, as it is now, should not compile. (The second argument of your JButton construtor is an Icon, not a String, java 8). So when you were getting the image from the file system, you were probably doing something else.
With your example, you need to read an image from the inputstream and convert it to an Icon:
try (InputStream is = getClass.getClassLoader().getResourcesAsStream("directory/image.jpg")) {
BufferedImage image = ImageIO.read(is);
return new JButton("Text", new ImageIcon(image));
} catch (IOException exc) {
throw new RuntimeException(exc);
}
That should use the image that is located in "directory" inside your jar. Of course, you need to include the image within your jar, or you will get a NullPointerException on the inputstream is.
I think you need to understand the
ClassLoader:
A typical strategy is to transform the name into a file name and then
read a "class file" of that name from a file system.
So with this you will be able to lead Resources of your project with getResource
public URL getResource(String name)
Finds the resource with the given name. A resource is some data
(images, audio, text, etc) that can be accessed by class code in a way
that is independent of the location of the code.
I'm sorry for asking such a beginner question, but I just can't get it to work and I can't find the answer anywere either.
I want to have an image inside my .jar file and load it. While that sounds simple, I was only able to load an image while running from inside the IDE but not anymore after making the .jar (Thanks to google I was able to get the .png inside the .jar). Here is what I tried:
BorderPane bpMain = new BorderPane();
String fs = File.separator;
Image imgManikin;
try {
imgManikin = new Image(
Main.class.getProtectionDomain().getCodeSource().getLocation().toURI().toString()+"\\manikin.png");
bpMain.setBottom(new Label(Main.class.getProtectionDomain().getCodeSource().getLocation().toURI().toString()+"\\manikin.png"));
} catch (URISyntaxException e) {
imgManikin = new Image(
Main.class.getProtectionDomain().getCodeSource().getLocation().getPath()+"\\manikin.png");
System.out.println(Main.class.getProtectionDomain().getCodeSource().getLocation().getPath()+"\\manikin.png");
bpMain.setBottom(new Label(Main.class.getProtectionDomain().getCodeSource().getLocation().getPath()+"\\manikin.png"));
}
//Image imgManikin = new Image("file:src\\manikin.png");
ImageView imgvBackground = new ImageView(imgManikin);
imgvBackground.setFitWidth(100);
imgvBackground.setPreserveRatio(true);
bpMain.setCenter(imgvBackground);
primaryStage.setTitle("Kagami");
primaryStage.setScene(new Scene(bpMain, 300, 275));
primaryStage.show();
Needlessly to say it didn't work. It is showing me the Label at the bottom with the path just as intended, but it seams like the path just isn't right. (I also tried using the File.seperator instead of \\ and even /, but I got the same result every time: It showes me the path but won't load the image.
I'm using Windows 7, the IDE is IntelliJ and I have the newest Java update.
If the jar file is on the classpath of your application and the image to be loaded is located at the root of the jar file, the image can be loaded easily by:
URL url = getClass().getResource("/manikin.png");
BufferedImage awtImg = ImageIO.read(url);
Image fxImg = SwingFXUtils.toFxImage(awtImg, new Image());
Image fxImgDirect = new Image(url.openStream());
While ImageIO returns a BufferedImage this can be converted to a fx Image using the SwingUtils. However the preferred way is to directly create a new Image instance using the InputStream from the URL.
See also Load image from a file inside a project folder. If done right it does not matter if it is loaded from a jar file or the local file system.
The Image::new(String) constructor is looking for a URL. It is possible to construct a URL for a resource in a jar file, but it's much easier to use ClassLoader::getResource or ClassLoader::getResourceAsStream to manage that for you.
Given the file structure:
src/
SO37054168/
GetResourceTest.java
example/
foo.txt
The following, packaged as a jar will output
package SO37054168;
public class GetResourceTest {
public static void main(String[] args) {
System.out.println(GetResourceTest.class.getClassLoader().getResource("example/foo.txt"));
System.out.println(GetResourceTest.class.getClassLoader().getResourceAsStream("example/foo.txt"));
}
}
jar:file:/home/jeffrey/Test.jar!/example/foo.txt
sun.net.www.protocol.jar.JarURLConnection$JarURLInputStream#7f31245a
Note how the URL for the resource is not the same as the URL you were trying to construct. The protocol is different, and you need to have the ! after the path to the jar file.
I need some help with importing Images to my JavaFx application:
My image has the path : /sprinter/ExternalSprinterFolder/Maps/map_asteroid/map_asteroid.jpg
My GUI code has the path:
/sprinter/src/de/sprinter/gameclient/gui/SelectSectorGui.java
I tried already a lot but I can't load the image...
I tried for example:
File file = new File(imagePath);
Image image = new Image(file.toURI().toString());
ImageView iv = new ImageView(image);
and
String image = SelectSectorGui.class.getResource(imagePath).toExternalForm();
pane.setStyle(("-fx-background-image: url(\" " + image +
" \");-fx-background-repeat: no-repeat;"));
The first code block is the correct way to do this if the file will be on the file system, and not bundled as part of your jar file. In that case imagePath should be the absolute filesystem path to the file. You can check if the file exists with
System.out.println(file.exists());
The second code block is the correct way to do this if the image file will be bundled in your jar file. In this case, imagePath should be relative to the class; an path starting with / is interpreted as being relative to the classpath. If the path is incorrect in this case, getResource(...) will return null.
i have a the path of an image in a string i want to display it on a jlabel using the path. please help me.
if(!ar.get(16).equals("empty")){
String photo=(String)ar.get(16);
System.out.println(photo);
// if(!photo.equals(""))
// pic.setText(photo);
Image image=Toolkit.getDefaultToolkit().getImage(photo);;
ImageIcon img=new ImageIcon(image.getScaledInstance(view.jLabel5.getWidth(), view.jLabel5.getHeight(), 0));
//JpegReader jrdr=new JpegReader();
//view.jLabel5.setSize(img, image.getWidth());
view.jLabel5.setPreferredSize(new Dimension(100, 100));
view.jLabel5.setIcon(img);
}
If the image is an embedded resources (ie lives within the application context/is bundled with the application Jar), then you need to use getResource to gain access to it..
Toolkit.getDefaultToolkit().getImage expects that the String passed to it is a file on the file system.
If the image is embedded, then you will need to use something more like...
Toolkit.getDefaultToolkit().getImage(getClass().getResource(photo))
To load it.
If the image is being loaded from the file system, you could use
File file = new File(photo);
if (file.exists()) {
// Attempt to load the image
} else {
// Show error message.
}
Because of the way Toolkit#getImage works, it will not provide any details if the image fails to load for some reason.
Instead, you should be using ImageIO, which will throw an IOException if it was unable to load the image for some reason...
BufferedImage img = ImageIO.read(getClass().getResource(photo));
or
BufferedImage img = ImageIO.read(new File(photo));
Depending on where the image is located.
Take a look at Reading/Loading an Image.
You should also avoid calling setPreferredSize explicitly and simply allow JLabel to make it's own choices...
Put the image file in the project. Under a seperate folder.
ImageIcon image = new ImageIcon(this.getClass().getResource("/images/abc.jpg"));
JLabel imageLabel = new JLabel(image, JLabel.CENTER);
If you want to load the image for any other location on your computer then,
ImageIcon image = new ImageIcon("C:/images/image.png");
JLabel imagelabel = new JLabel(image);
Make sure your paths are correct. If you photo string path is "photo.jpeg", your path should look something like this
ProjectRoot
photo.jpeg
src
If you want to put the photo.jpeg in a directory images, you should use "images/photo.jpeg"
ProjectRoot
images
photo.jpeg
src
This is considering you're using an IDE like Netbeans or Ecplise.
I have a Java project with a toolbar, and the toolbar has icons on it. These icons are stored in a folder called resources/, so for example the path might be "resources/icon1.png". This folder is located in my src directory, so when it is compiled the folder is copied into bin/
I'm using the following code to access the resources.
protected AbstractButton makeToolbarButton(String imageName, String actionCommand, String toolTipText,
String altText, boolean toggleButton) {
String imgLocation = imageName;
InputStream imageStream = getClass().getResourceAsStream(imgLocation);
AbstractButton button;
if (toggleButton)
button = new JToggleButton();
else
button = new JButton();
button.setActionCommand(actionCommand);
button.setToolTipText(toolTipText);
button.addActionListener(listenerClass);
if (imageStream != null) { // image found
try {
byte abyte0[] = new byte[imageStream.available()];
imageStream.read(abyte0);
(button).setIcon(new ImageIcon(Toolkit.getDefaultToolkit().createImage(abyte0)));
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
imageStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} else { // no image found
(button).setText(altText);
System.err.println("Resource not found: " + imgLocation);
}
return button;
}
(imageName will be "resources/icon1.png" etc). This works fine when run in Eclipse. However, when I export a runnable JAR from Eclipse, the icons are not found.
I opened the JAR file and the resources folder is there. I've tried everything, moving the folder, altering the JAR file etc, but I cannot get the icons to show up.
Does anyone know what I'm doing wrong?
(As a side question, is there any file monitor that can work with JAR files? When path problems arise I usually just open FileMon to see what's going on, but it just shows up as accessing the JAR file in this case)
Thank you.
I see two problems with your code:
getClass().getResourceAsStream(imgLocation);
This assumes that the image file is in the same folder as the .class file of the class this code is from, not in a separate resources folder. Try this instead:
getClass().getClassLoader().getResourceAsStream("resources/"+imgLocation);
Another problem:
byte abyte0[] = new byte[imageStream.available()];
The method InputStream.available() does not return the total number of bytes in the stream! It returns the number of bytes available without blocking, which is often much less.
You have to write a loop to copy the bytes to a temporary ByteArrayOutputStream until the end of the stream is reached. Alternatively, use getResource() and the createImage() method that takes an URL parameter.
To load an image from a JAR resource use the following code:
Toolkit tk = Toolkit.getDefaultToolkit();
URL url = getClass().getResource("path/to/img.png");
Image img = tk.createImage(url);
tk.prepareImage(img, -1, -1, null);
The section from the Swing tutorial on How to Use Icons shows you how to create a URL and read the Icon in two statements.
For example in a NetBeans project, create a resources folder in the src folder. Put your images (jpg, ...) in there.
Whether you use ImageIO or Toolkit (including getResource), you must include a leading / in your path to the image file:
Image image = Toolkit.getDefaultToolkit().getImage(getClass().getResource("/resources/agfa_icon.jpg"));
setIconImage(image);
If this code is inside your JFrame class, the image is added to the frame as an icon in your title bar.