繁体   English   中英

如何获取文件的所有不同大小的系统图标

[英]How to get all different sizes of system icon of a file

我正在用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 。 两种“解决方案”都已经在这里讨论

我遇到了需要高分辨率图标的相同问题。 经过一个小时的挖掘,我认为答案很清楚,尽管很不幸。

  1. 目前没有本机库支持。
  2. 预计 Java 版本 12 将提供本机支持。
  3. 即使经过大量搜索,我也找不到任何可靠的第三方库。

这个问题的票已经提交这里的JDK错误的系统,但似乎他们的优先清单上相当低。


但是,似乎确实有解决方法:

我假设您使用的是 Windows。 在 Linux 上查找图标文件很简单,因为图标单独存储并链接在桌面条目中。

  1. 使用第三方命令行 exe 工具将图标解压缩到临时目录中,例如this onethis one 您可以使用Runtime.exec()
  2. 使用像这里建议的那样.ico 阅读器库它包含的所有图像文件读入List BufferedImage
  3. 遍历列表以找到分辨率最高的图像。
  4. 删除临时文件。

更新

刚刚实施了我的解决方法,它奏效了。 这是代码片段。 我在我的实现中使用了iconsext.exeimage4j

    // 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");

你有图标。

如果您正在寻找如何在 Mac 上执行此操作,您可以使用第三方库Quaqua

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);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM