小编典典

如何在Java中将.TIF图像设置为ImageIcon?

java

谁能建议我如何将.TIF格式的图像存储到ImageIcon该图像并将其添加到列表模型?我试过了,但是给了我java.lang.NullPointerException

  public static void main(String[] args) throws Exception {
    String path = "C:\\project\\aimages";
    JFrame frame = new JFrame();
    frame.setSize(500, 500);
    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

    File folder = new File(path);
    File[] listOfFiles = folder.listFiles();
    DefaultListModel listModel = new DefaultListModel();
    System.out.println("listOfFiles.length="+listOfFiles.length);
    int count = 0;
    for (int i = 0; i < listOfFiles.length; i++) {
        //System.out.println("check path"+listOfFiles[i]);
        String name = listOfFiles[i].toString();
         System.out.println("name"+name);
        // load only JPEGs
        if (name.endsWith("jpg") || name.endsWith("JPG")|| name.endsWith("tif") || name.endsWith("TIF")) {
            if(name.endsWith("tif") || name.endsWith("TIF"))
            { 
                BufferedImage image = ImageIO.read(listOfFiles[i]);
           BufferedImage convertedImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB);
              ImageIcon ii = new ImageIcon(image);
                    Image img1 = ii.getImage();
                Image newimg = img1.getScaledInstance(75, 75, java.awt.Image.SCALE_SMOOTH);
                   ImageIcon newIcon = new ImageIcon(img1);
                  listModel.add(count++, newIcon);
            }
            else
            {
              ImageIcon ii = new ImageIcon(ImageIO.read(listOfFiles[i]));
              Image img1 = ii.getImage();
              Image newimg = img1.getScaledInstance(75, 75, java.awt.Image.SCALE_SMOOTH);
              ImageIcon newIcon = new ImageIcon(newimg);
             listModel.add(count++, newIcon);
            }
        }
    }
    JList p2 = new JList(listModel);

    }
     }

在这里,我编辑了代码,这是我的错误msg
异常,位于ListImage1.main(ListImage1.java:48)的javax.swing.ImageIcon。(ImageIcon.java:228)的线程“
main”中java.lang.NullPointerException


阅读 212

收藏
2020-11-26

共1个答案

小编典典

如果TIFF是应用程序资源,则最好将其转换为JPG或PNG。

OTOH,我相信JAI为阅读TIFF提供了支持。

2020-11-26