1

我正在使用 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!!!");
    }
}

我的问题是大型文件夹和扫描驱动器时速度很慢。请建议提高速度的方法

4

1 回答 1

1

ImageIO.read()与图像阅读器的本机实现(在 C++ 中)相比,它本身非常慢。但是,当您使用以下代码调整图像大小时:

AffineTransform af = new AffineTransform(AffineTransform.getScaleInstance(width/img.getWidth(), (height/img.getHeight()))); 
        img = new AffineTransformOp(af, AffineTransformOp.TYPE_NEAREST_NEIGHBOR).filter(img, null);

这很慢,缩放质量很差。请阅读这篇文章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 中有已知的库,可以在最佳时间成本下提供更高质量的缩放图像:

  1. imgscalr
  2. java图像缩放
于 2013-10-05T09:33:18.230 回答