我正在使用swing创建一个图像托盘。它的作用是找到文件夹或驱动器中的所有图像文件,然后将这些文件添加到实际上是JPanel的托盘中。代码如下:
public void findAllPhotos(File f ) {
File[] files = f.listFiles();
for (File file : files) {
if(file.isFile()) {
String path = file.getAbsolutePath();
for(String s : extensions) {
if(path.endsWith(s)) {
addImageToTray(file);
break;
}
}
}
else {
findAllPhotos(file);
}
}
}
void addImageToTray(File fname) {
try {
BufferedImage img = ImageIO.read(fname);
if(img == null) return;
double width = 0, height = 0;
if(iconView) {
width = Math.min(img.getWidth(), iconWidth);
height = Math.min(img.getHeight(), iconHeight);
}
else {
width = Math.min(img.getWidth(), tileWidth);
height = Math.min(img.getHeight(), tileHeight);
}
AffineTransform af = new AffineTransform(AffineTransform.getScaleInstance(width/img.getWidth(), (height/img.getHeight())));
img = new AffineTransformOp(af, AffineTransformOp.TYPE_NEAREST_NEIGHBOR).filter(img, null);
JLabel jl = new JLabel(new ImageIcon(img));
if(iconView) {
jl.setText(" " +fname.getName());
jl.setFont(new java.awt.Font("Microsoft JhengHei UI Light", 1, 11));
}
addActionListner(jl, fname.getAbsolutePath());
jl.setBorder(new BevelBorder(BevelBorder.LOWERED));
tray.add(jl);
} catch (IOException ex) {
JOptionPane.showMessageDialog(null, "unknown problem, with tray creation!!!");
}
}
我的问题是大型文件夹和扫描驱动器时速度很慢。 请建议提高速度的方法
答案 0 :(得分:1)
ImageIO.read()
本身相当慢。但是,当您使用以下代码调整图像大小时:
AffineTransform af = new AffineTransform(AffineTransform.getScaleInstance(width/img.getWidth(), (height/img.getHeight())));
img = new AffineTransformOp(af, AffineTransformOp.TYPE_NEAREST_NEIGHBOR).filter(img, null);
速度慢,标准质量很差。请仔细阅读本文The Perils of Image.getScaledInstance(),了解缩放图片及其性能问题的各种技巧。快速扩展和更好性能的快速解决方案将使用以下代码:
private static GraphicsConfiguration getGraphicsConfiguration() {
return GraphicsEnvironment.getLocalGraphicsEnvironment().
getDefaultScreenDevice().getDefaultConfiguration();
}
BufferedImage tmpImage = getGraphicsConfiguration().create(newWidth, newHeight, Transparency.TRANSLUCENT);
Graphics2D g2d = (Graphics2D)tmpImage.getGraphics();
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.drawImage(image, 0, 0, newWidth, newHeight, null);
tmpImage
现在是新的缩放图像。表现更好。纯java中有一个已知的库,它可以以最佳的时间成本提供更高质量的缩放图像: