nick zoum
nick zoum

Reputation: 7325

Get a specific version of the icon of a file in Java

I was looking at this question and I was looking at the first answer.

So I tried to use this code:

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

Which does return an Image (or throws an Error) but the Image has terribly low resolution.

I am assuming that this is because the 16x16 Image is returned.

Is there any way to state which Image I want to be returned?

Upvotes: 2

Views: 277

Answers (2)

ArcticLord
ArcticLord

Reputation: 4039

Java offers you two possibilities to retrieve file icons.
You already know the first one:

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

that gives you a 16x16 pixel result.

The other one using ShellFolder

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

will retrieve you the larger one (32x32) depending on the boolean flag getLargeIcon in the getIcon method.
I'm sorry for you but more is (at the moment) not possible with the java default libraries. Interest exists as you can read in this JDK bugreport. But nothing has been done so far.

If you really want to have larger versions you will need to retrieve them with the OS depending native calls or store them manually as local application ressources.

Note: If you have problems accessing ShellFolder you should read this question.

Upvotes: 2

aurox
aurox

Reputation: 117

I used this method:

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

where getScaledImage is:

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

Upvotes: 0

Related Questions