如何在Java中将.TIF图像设置为ImageIcon? [英] How to set .TIF image to ImageIcon in java?
问题描述
有人可以建议我如何将.TIF格式的图像存储到ImageIcon
并将该图像添加到列表模型中吗?我试过了,但是给了我java.lang.NullPointerException
.
Could anyone suggest me how to store .TIF formatted image to ImageIcon
and add this image to list model? I tried this but gives me 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);
}
}
在这里我已经编辑了代码,这是我的错误信息 线程主"中的异常java.lang.NullPointerException 在javax.swing.ImageIcon(ImageIcon.java:228) 在ListImage1.main(ListImage1.java:48)
here i had edited my code and this is my error msg Exception in thread "main" java.lang.NullPointerException at javax.swing.ImageIcon.(ImageIcon.java:228) at ListImage1.main(ListImage1.java:48)
推荐答案
如果TIFF是应用程序资源,则最好将其转换为JPG或PNG.
If the TIFF is an application resource, probably better to convert it to JPG or PNG.
OTOH,我相信 JAI 支持阅读TIFF
OTOH, I believe that JAI offers support for reading TIFF.
这篇关于如何在Java中将.TIF图像设置为ImageIcon?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!