我正在编写一段Java代码,需要获取文件系统图标的不同大小。我知道要获取文件系统图标,应该使用以下代码:
File file = new File("Whatever.txt");
FileSystemView view = FileSystemView.getFileSystemView();
Icon icon = view.getSystemIcon(file);
但是这段代码只返回图标的最小尺寸。我该怎么做才能获取其他尺寸呢?
对于32x32的图标,您可以使用ShellFolder。
sun.awt.shell.ShellFolder.getShellFolder( file ).getIcon( true )
或者使用JNI API。这两种“解决方案”已经在这里讨论过了。
我也遇到了需要高清晰度图标的同样问题。经过一个小时的挖掘,我认为答案相当明确,尽管非常不幸。
已经在JDK bug系统这里提交了此问题的工单,但它似乎不在他们的优先级列表中。
然而,似乎有解决方法:
我假设您正在使用Windows。在Linux上查找图标文件很容易,因为图标是单独存储并链接到桌面条目中的。
Runtime.exec()
。List
中的BufferedImage
。更新
刚刚实现了我的解决方法,它起作用了。这是代码片段。我在我的实现中使用了iconsext.exe和image4j。
// Extract icons and wait for completion.
File iconDir = new File("tempIcons");
String[] iconsextCmd = { "iconsext.exe", "/save", exeFile.getPath(), iconDir.getPath(), "-icons" };
Process iconsextProc = Runtime.getRuntime().exec(iconsextCmd);
iconsextProc.waitFor();
// Get all icons, sort by ascending name, and pick first one.
File[] icons = iconDir.listFiles();
Arrays.sort(icons, (f1, f2) -> f1.getName().compareTo(f2.getName()));
File defaultIcon = icons[0];
// Read images from icon.
List<ICOImage> iconImgs = ICODecoder.readExt(defaultIcon);
// Sort images by descending size and color depth, and pick first one.
iconImgs.sort((i1, i2) -> (i2.getWidth() * i2.getHeight() * 33 + i2.getColourDepth())
- (i1.getWidth() * i1.getHeight() * 33 + i1.getColourDepth()));
BufferedImage awtImg = iconImgs.get(0).getImage();
// Delete temporary icons.
for (File i : icons)
{
i.delete();
}
iconDir.delete();
加入一些JavaFX代码:
漂亮又大的图标!
我知道这个解决方法有些麻烦和复杂,而且它也抵消了Java跨平台的优势,但说实话这是我能想到的最好的方法。希望能对你有所帮助。
我创建了一个名为JIconExtractReloaded的库,可以提取所有图标大小,而不仅仅是32x32。这是链接https://github.com/MrMarnic/JIconExtractReloaded。
只需编写:
BufferedImage image = JIconExtract.getIconForFile(128,128,"C:\\Windows\\explorer.exe");
而且你有图标。
import java.awt.image.BufferedImage;
import java.io.File;
public class SystemIconMac {
public static BufferedImage getIconImage(File file, int size) {
return ch.randelshofer.quaqua.osx.OSXFile.getIconImage(file, size);
}
}
Icon[]
的方法。 - Andrew Thompson