Java-获取文件缩略图并调整大小
我正在尝试获取与特定文件关联的缩略图,然后调整其大小。我一直在Mac上进行测试,但还没有找到一个解决方案来实现这一点 迄今为止的代码:Java-获取文件缩略图并调整大小,java,swing,Java,Swing,我正在尝试获取与特定文件关联的缩略图,然后调整其大小。我一直在Mac上进行测试,但还没有找到一个解决方案来实现这一点 迄今为止的代码: import com.apple.laf.AquaIcon; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; public class
import com.apple.laf.AquaIcon;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
public class TestSystemIcon extends JFrame
{
JPanel panel;
ImageIcon icon;
public TestSystemIcon()
{
panel = new JPanel();
JButton button = new JButton("Open...");
final JLabel label = new JLabel();
icon = null;
final JPanel en = new JPanel(new FlowLayout(FlowLayout.CENTER));
label.setHorizontalAlignment(SwingConstants.CENTER);
button.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
JFileChooser fileChooser = new JFileChooser();
if(fileChooser.showOpenDialog(null) == JFileChooser.OPEN_DIALOG)
{
File file = fileChooser.getSelectedFile();
icon = resizeIcon(getThumbnail1(file),200,200);
// icon = resizeIcon(getThumbnail2(file),200,200);
System.out.println(icon);
label.setIcon(icon);
en.add(label);
revalidate();
repaint();
}
}
});
panel.add(button);
this.add(panel,BorderLayout.NORTH);
this.add(en,BorderLayout.CENTER);
this.setSize(400,400);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public ImageIcon getThumbnail1(File file)
{
JFileChooser f = new JFileChooser();
Icon i = f.getIcon(file);
//Mac Conversion.
Image image = AquaIcon.getImageForIcon(i);
return new ImageIcon(image);
}
public ImageIcon getThumbnail2(File file)
{
return new ImageIcon(file.getPath());
}
public ImageIcon resizeIcon(ImageIcon imageIcon,int width, int height)
{
return new ImageIcon(imageIcon.getImage().getScaledInstance(width,height,Image.SCALE_SMOOTH));
}
public static void main(String[] args)
{
TestSystemIcon test = new TestSystemIcon();
test.setVisible(true);
}
}
获取缩略图的版本1具有以下行为:
- 可以打开缩略图
- 非常小,不适合缩放
- 不显示图像,尽管找到图像(System.out证明了这一点)。 除了pdf,它显示的是实际文件,而不是 缩略图
- 当它工作时,例如pdf,它可以很好地扩展
sun.awt.shell.ShellFolder代码>,但我的目标是跨平台解决方案
感谢您提供的帮助我查看了我以前编写的一些代码,当您使用JLabel with和ImageIcon时,这似乎很好。请尝试将大图像大小调整为100x100的代码
ImageIcon icon = new ImageIcon("Penguins.jpg");
Image img = icon.getImage().getScaledInstance(100,100,Image.SCALE_SMOOTH);
// if the file is not an image, but a file on the system,
Icon icon = FileSystemView.getFileSystemView().getSystemIcon(file);
Image img = ((ImageIcon) icon).getImage().getScaledInstance(100,100,Image.SCALE_SMOOTH);
ImageIcon icon1 = new ImageIcon(img);
JLabel image = new JLabel(icon1);
感谢您的回复,不过目的是获取任何文件的缩略图,而不是图像。i、 如果我打开一个docx文档,我会得到microsoftword的缩略图icon@EII_18,我发现了一个重复的帖子,它解决了图标问题,但没有重新调整图像问题的大小,请看我尝试了它的工作逻辑,但是如果需要重新调整图标,请使用我回答中的逻辑。我更新了答案,以显示1498506帖子中提供的信息。