如何使用其路径显示图像 [英] how to display image using its path

查看:102
本文介绍了如何使用其路径显示图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串图像的路径,我想使用该路径在jlabel上显示它.请帮助我.

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

}

推荐答案

如果图像是嵌入式资源(即位于应用程序上下文中/与应用程序Jar捆绑在一起),则需要使用getResource来获取访问它..

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期望传递给它的String是文件系统上的文件.

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

要加载它.

如果正在从文件系统加载图像,则可以使用

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

由于Toolkit#getImage的工作方式,如果图像由于某种原因无法加载,它将不会提供任何详细信息.

Because of the way Toolkit#getImage works, it will not provide any details if the image fails to load for some reason.

相反,您应该使用ImageIO,如果由于某种原因而无法加载图像,则会抛出IOException.

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

BufferedImage img = ImageIO.read(new File(photo));

取决于图像所在的位置.

Depending on where the image is located.

看看读取/加载图像.

您还应该避免显式调用setPreferredSize,而只允许JLabel自行选择...

You should also avoid calling setPreferredSize explicitly and simply allow JLabel to make it's own choices...

这篇关于如何使用其路径显示图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆