jaseem
jaseem

Reputation: 21

how to display image using its path

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);

}

Upvotes: 1

Views: 3272

Answers (3)

MadProgrammer
MadProgrammer

Reputation: 347194

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...

Upvotes: 3

Sorter
Sorter

Reputation: 10220

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);

Upvotes: 1

Paul Samsotha
Paul Samsotha

Reputation: 208984

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.

Upvotes: 0

Related Questions