I try to display an image using a JLabel. This is my project navigator:
From SettingsDialog.java I want to display an image using following code:
String path = "/images/sidebar-icon-48.png";
File file = new File(path);
Image image;
try {
image = ImageIO.read(file);
JLabel label = new JLabel(new ImageIcon(image));
header.add(label); // header is a JPanel
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The code throws an exception: Can't read input file!
Is the path of the image is wrong?
Don't read from a file, read from the class path
image = ImageIO.read(getClass().getResource(path));
-or-
image = ImageIO.read(MyClass.class.getResource(path));
When you use a File object, you're telling the program to read from the file system, which will make your path invalid. The path you are using is correct though, when reading from the class path, as you should be doing.
See the wiki on embedded resource. Also see getResource()
UPDATE Test Run
package org.apache.openoffice.sidebar;
import javax.swing.*;
public class SomeClass {
public SomeClass() {
ImageIcon icon = new ImageIcon(
SomeClass.class.getResource("/images/sidebar-icon-48.png"));
JLabel label = new JLabel(icon);
JFrame frame = new JFrame("Test");
frame.add(label);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
new SomeClass();
}
});
}
}
"/images/sidebar-icon-48.png" is root path. On windows would be c:\images\sidebar-icon-48.png or d:\images\sidebar-icon-48.png depending on current drive (java converts the / to \ - not an issue). Linux images would a child of root /images/sidebar-icon-48.png Need to load relative to class or relative to the jar that had the class (if you do not want to store images inside jar.
In big projects its nice to have images and other resources outside the jar so the jar is smaller and more importantly its easy to change the resources without fiddling with jars/ wars.
Since you seem to be making a add on for open office, you will have to keep everything in jar and so peeskillet answer is right. But make sure your images folder is being packed in the jar. Extract the jar ising the jar command or rename the file to zip and extract.
Or check and fix project settings. How to make a jar in eclipse ... latest one has a wizard that makes an ant script or this SO
try to use this directly :
JLabel label = new JLabel(new ImageIcon(path));
and delete these line :
File file = new File(path);
image = ImageIO.read(file);
if error still exist paste the following error
Related
I have coded a program in Eclipse and it works properly when I run in that.
public static void initialize() throws IOException{
JTextField tfQrText;
int size = 250;
File qrFile;
BufferedImage qrBufferedImage;
JFrame gui = new JFrame("qrCode Generator");
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setSize(250, 340);
gui.setLayout(new BorderLayout());
gui.setResizable(false);
File iconFile = new File(VisualQrCodeGenerator.class.getResource("icon.png").getFile());
BufferedImage iconBuffered = ImageIO.read(iconFile);
gui.setIconImage(iconBuffered);
JButton generate = new JButton("Generate qrCode");
gui.add(generate,BorderLayout.SOUTH);
tfQrText = new JTextField();
PromptSupport.setPrompt("Enter Your Text ... ", tfQrText);
gui.add(tfQrText,BorderLayout.NORTH);
qrFile = new File(VisualQrCodeGenerator.class.getResource("qrCodeImage.png").getFile());
qrBufferedImage = ImageIO.read(qrFile);
ImageIcon qrImageIcon = new ImageIcon(qrBufferedImage);
JLabel image = new JLabel();
image.setIcon(qrImageIcon);
image.setHorizontalAlignment(JLabel.CENTER);
gui.add(image,BorderLayout.CENTER);
gui.setVisible(true);
generate.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
if(!(tfQrText.getText().equals(""))){
//create() Method make the QRcode Image
create();
}
}
});
The Error occurs on line:
BufferedImage iconBuffered = ImageIO.read(iconFile);
When I make it .jar file, it says:
My Project structure is like this:
+src
+qrCodeGenerator
-VisualQrCodeGenerator
-icon.png
-qrCodeImage.png
The code is running properly and without any error in program and I can work with it. But when I make it .jar file, it errors me as I uploaded it image.
This is normal: you can't access a classpath resource as a File object. This is because it is embedded inside a JAR. It works inside your IDE because resources are typically stored inside a temporary folder (and not inside a JAR).
You need to access it with an InputStream using Class.getResourceAsStream and use ImageIO.read(InputStream) instead.
As such, change your code to:
qrBufferedImage = ImageIO.read(VisualQrCodeGenerator.class.getResourceAsStream("qrCodeImage.png"));
and
iconBuffered = ImageIO.read(VisualQrCodeGenerator.class.getResourceAsStream("icon.png"));
I know what the problem is I just do not know how to fix it. So I have an image that I am trying to render in my program. I use ImageIO to load the image. But it seems to have a problem wit the path I am giving it. I am using NetBeans as my IDE and I dont know if I am saving the image file correctly.
First method:
public void init(){
BufferedImageLoader loader = new BufferedImageLoader();
try{
spriteSheet = loader.loadImage("/sprite_sheet.png");
}catch(IOException e){
e.printStackTrace();
}
SpriteSheet ss = new SpriteSheet(spriteSheet);
player = ss.grabImage(1,1,32,32);
}
the loader BufferedImageLoader class:
public class BufferedImageLoader {
private BufferedImage image;
public BufferedImage loadImage(String path) throws IOException{
image = ImageIO.read(getClass().getResource(path));
return image;
}
}
I have the image saved under a 'res' folder under 'src' folder.
Error:
Exception in thread "Thread-2" java.lang.IllegalArgumentException: input == null!
Thank you.
Why do you need to use getClass().getResource() ?
Most simple usage of ImageIO.read is as follows.
image = ImageIO.read(new File(path));
You may need to add folders to path also.
spriteSheet = loader.loadImage("/src/res/sprite_sheet.png");
Try using an absolute path for your file or if you need a relative check this post (eg assuming you have a res folder under default package did you try "/res/yourfile"
I'm using eclipse to created an RCP Application, and I'm not being able to load an image because I don't know how to find it in the generated code. I'm going to try to explain my particular issue.
Note: the project is a Game editor, and it is located here: http://chelder86.github.com/ArcadeTongame/
Firstly, this is the project structure:
The next code runs the RCP application correctly inside Eclipse, after changing the Working Workspace in the Eclipse Running Config.
package figures;
(...)
public class Sound extends ImageFigure {
public Sound() {
String picturePath = "src/figures/Sound48.png";
// or String picturePath = "bin/figures/Sound48.png";
Image image = new Image(null, picturePath);
this.setImage(image);
}
}
But it does not work when I create a Product and export it as an RCP Application. I mean, the RCP application works, but it does not load that image.
Note: build.properties has the image checked.
I tried different combinations like these with the same result: java.io.FileNotFoundException, when I run it in Eclipse:
package figures;
(...)
public class Sound extends ImageFigure {
public Sound() {
String picturePath = getClass().getResource("Sound48.png").getPath();
// or String picturePath = this.getClass().getClassLoader().getResource("bin/figures/Sound48.png").getPath();
// or String picturePath = this.getClass().getClassLoader().getResource("figures/Sound48.png").getHost();
// or similars
Image image = new Image(null, picturePath);
this.setImage(image);
}
}
How could I load it correctly?
Thanks for any help! :)
Carlos
Try creating a separate "figures" folder alongside "icons" folder. Put only the image files there, not .java files. Don't forget to add it to the class path and to build.properties. Then something like this should work:
InputStream in = getClass().getResourceAsStream("figures/Sound48.png");
Image image = new Image(Display.getDefault(), in);
I have a JEditorPane created by this way:
JEditorPane pane = new JEditorPane("text/html", "<font face='Arial'>" + my_text_to_show + "<img src='/root/img.gif'/>" + "</font>");
I put this pane on a JFrame.
Text is shown correctly, but I can't see the picture, there is only a square indicating that there should be an image (i.e.: "broken image" shown by browsers when picture has not been found)
You have to provide type, and get the resource. That's all. My tested example, but I'm not sure about formating. Hope it helps:
import java.io.IOException;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
public class Test extends JFrame {
public static void main(String[] args) throws Exception {
Test.createAndShowGUI();
}
private static void createAndShowGUI() throws IOException {
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("HelloWorldSwing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
String imgsrc =
Test.class.getClassLoader().getSystemResource("a.jpg").toString();
frame.getContentPane().add(new JEditorPane("text/html",
"<html><img src='"+imgsrc+"' width=200height=200></img>"));
frame.pack();
frame.setVisible(true);
}
}
The JEditorPane is using HTMLDocument.getBase to locate relative urls as well, so if you are displaying content from a directory, make sure to set the base on the html document so it resolves urls relative to the base directory.
Depending on where that image actually is, you might want to extend HTMLEditorKit+HTMLFactory+ImageView and provide a custom implementation of ImageView, which is responsible for mapping the attribute URL to the image URL, too.
None of the above worked for me, however 'imgsrc = new File("passport.jpg").toURL().toExternalForm();' let me to try and have each image in the html have a preceding 'file:' so that it now reads:
<img src="file:passport.jpg" />
And that works fine for me.
If you want to specify relative path to the image.
Let's say your project folder structure is as following:
sample_project/images
sample_project/images/loading.gif
sample_project/src
sampler_project/src/package_name
Now the image tag would look like this:
"<img src='file:images/loading.gif' width='100' height='100'>"
Yaay!
I used this when I was working in netbeans, it worked though. I think a little modification if the program should run outside of netbeans,
String imgsrc="";
try {
imgsrc = new File("passport.jpg").toURL().toExternalForm();
} catch (MalformedURLException ex) {
Logger.getLogger(EntityManager.class.getName()).log(Level.SEVERE, null, ex);
}
//System.out.println(imgsrc); use this to check
html = "<img src='" + imgsrc + "' alt='' name='passport' width='74' height='85' /><br />";
//use the html ...
if you run from the jar, the image file has to be on the same directory level, ...
in fact, the image file has to be on the same directory as your execution entry.
I'm using NetBeans, trying to change the familiar Java coffee cup icon to a png file that I have saved in a resources directory in the jar file. I've found many different web pages that claim they have a solution, but so far none of them work.
Here's what I have at the moment (leaving out the try-catch block):
URL url = new URL("com/xyz/resources/camera.png");
Toolkit kit = Toolkit.getDefaultToolkit();
Image img = kit.createImage(url);
getFrame().setIconImage(img);
The class that contains this code is in the com.xyz package, if that makes any difference. That class also extends JFrame. This code is throwing a MalformedUrlException on the first line.
Anyone have a solution that works?
java.net.URL url = ClassLoader.getSystemResource("com/xyz/resources/camera.png");
May or may not require a '/' at the front of the path.
You can simply go Netbeans, in the design view, go to JFrame property, choose icon image property, Choose Set Form's iconImage property using: "Custom code" and then in the Form.SetIconImage() function put the following code:
Toolkit.getDefaultToolkit().getImage(name_of_your_JFrame.class.getResource("image.png"))
Do not forget to import:
import java.awt.Toolkit;
in the source code!
Or place the image in a location relative to a class and you don't need all that package/path info in the string itself.
com.xyz.SomeClassInThisPackage.class.getResource( "resources/camera.png" );
That way if you move the class to a different package, you dont have to find all the strings, you just move the class and its resources directory.
Try This write after
initcomponents();
setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("Your image address")));
/** Creates new form Java Program1*/
public Java Program1()
Image im = null;
try {
im = ImageIO.read(getClass().getResource("/image location"));
} catch (IOException ex) {
Logger.getLogger(chat.class.getName()).log(Level.SEVERE, null, ex);
}
setIconImage(im);
This is what I used in the GUI in netbeans and it worked perfectly
In a class that extends a javax.swing.JFrame use method setIconImage.
this.setIconImage(new ImageIcon(getClass().getResource("/resource/icon.png")).getImage());
You should define icons of various size, Windows and Linux distros like Ubuntu use different icons in Taskbar and Alt-Tab.
public static final URL ICON16 = HelperUi.class.getResource("/com/jsql/view/swing/resources/images/software/bug16.png");
public static final URL ICON32 = HelperUi.class.getResource("/com/jsql/view/swing/resources/images/software/bug32.png");
public static final URL ICON96 = HelperUi.class.getResource("/com/jsql/view/swing/resources/images/software/bug96.png");
List<Image> images = new ArrayList<>();
try {
images.add(ImageIO.read(HelperUi.ICON96));
images.add(ImageIO.read(HelperUi.ICON32));
images.add(ImageIO.read(HelperUi.ICON16));
} catch (IOException e) {
LOGGER.error(e, e);
}
// Define a small and large app icon
this.setIconImages(images);
You can try this one, it works just fine :
` ImageIcon icon = new ImageIcon(".//Ressources//User_50.png");
this.setIconImage(icon.getImage());`
inside frame constructor
try{
setIconImage(ImageIO.read(new File("./images/icon.png")));
}
catch (Exception ex){
//do something
}
Example:
URL imageURL = this.getClass().getClassLoader().getResource("Gui/icon/report-go-icon.png");
ImageIcon iChing = new ImageIcon("C:\\Users\\RrezartP\\Documents\\NetBeansProjects\\Inventari\\src\\Gui\\icon\\report-go-icon.png");
btnReport.setIcon(iChing);
System.out.println(imageURL);