【问题标题】:Get a specific version of the icon of a file in Java获取Java中文件图标的特定版本
【发布时间】:2017-02-16 12:38:12
【问题描述】:

我在看这个question,我在看第一个答案。

所以我尝试使用这段代码:

public static Image getIcon(String fileName) throws Exception {
    File file = new File(fileName);
    FileSystemView view = FileSystemView.getFileSystemView();
    Icon icon = view.getSystemIcon(file);
    ImageIcon imageIcon = (ImageIcon) icon;
    Image image = imageIcon.getImage();
    return image;
}

确实会返回 Image(或抛出 Error),但 Image 的分辨率非常低。

我假设这是因为返回了 16x16 Image

有什么方法可以说明我想退回哪个Image

【问题讨论】:

  • “特定版本”和“哪个图像”是指系统提供的相同类型的图像,但分辨率更高,例如 48×48,对吗?
  • @VGR 没错
  • @MikhailKuchma Java 找不到方法,我得到NoSuchMethodException

标签: java file filesystems icons thumbnails


【解决方案1】:

Java 为您提供了两种检索文件图标的可能性。
你已经知道第一个了:

Icon icon = FileSystemView.getFileSystemView().getSystemIcon(new File(FILENAME));

这将为您提供 16x16 像素的结果。

另一个使用ShellFolder

Icon icon = new ImageIcon(ShellFolder.getShellFolder(new File(FILENAME)).getIcon(true));

将根据 getIcon 方法中的布尔标志 getLargeIcon 为您检索较大的 (32x32)。
很抱歉,但是(目前)Java 默认库无法实现更多功能。您可以阅读in this JDK bugreport,从而产生兴趣。 但是到目前为止还没有做任何事情。

如果您真的想要更大的版本,您需要使用操作系统根据本机调用来检索它们,或者将它们手动存储为本地应用程序资源。

注意:如果您在访问 @ 时遇到问题987654328@你应该读this question

【讨论】:

  • 那么方法getIcon如果参数为真则返回大图,如果参数为假则返回小图?所以这个:return ShellFolder.getShellFolder(new File(fileName)).getIcon(true); 会返回最佳分辨率的图像吗?
  • 没错。这是你能得到的最好的。
  • 从以前开始,分辨率肯定有所提高。所以谢谢。
【解决方案2】:

我用了这个方法:

protected ImageIcon getImageIcon() {
    File f = new File((iconPath!=null)?iconPath:"");
    if (!f.isFile() || !f.canRead()) {
        iconPath = Constants.getDefaultPreviewIconPath();
    }
    ImageIcon icon = new ImageIcon(iconPath, titolo);
    return new ImageIcon(Utils.getScaledImage(
            icon.getImage(), 
            Constants.getICON_WIDTH(), 
            Constants.getICON_HEIGTH()));
}

getScaledImage 在哪里:

public static Image getScaledImage(Image srcImg, int w, int h) {
        BufferedImage resizedImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = resizedImg.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g2.drawImage(srcImg, 0, 0, w, h, null);
        g2.dispose();
        return resizedImg;
    }

【讨论】:

  • 放大 16×16 图像与检索系统的更高分辨率版本的图像不同。
  • "titolo" 是一个字符串,用作描述是我的类的一个字段,与 "iconPath" 相同
  • @VGR 好的,我误解了问题
猜你喜欢
  • 1970-01-01
  • 2016-01-01
  • 1970-01-01
  • 2020-09-23
  • 2012-06-16
  • 2011-01-07
  • 2014-01-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多