gpt4 book ai didi

java - 使用 swing 创建图像托盘

转载 作者:太空宇宙 更新时间:2023-11-04 07:21:56 30 4
gpt4 key购买 nike

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

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

最佳答案

与图像读取器的 native 实现(在 C++ 中)相比,

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 中有一些已知的库,可以以最佳的时间成本提供更高质量的缩放图像:

  1. imgscalr
  2. java-image-scaling

关于java - 使用 swing 创建图像托盘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19195948/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com