java swing 获取文件icon
public static void main(String[] args) {
getIcon("D://file/image.jpg");
}
public static void getIcon(String filePath) {
// 获取要读取的文件
File file = new File(filePaht);
// 创建文件系统视图,它会关联到当前平台的文件浏览器
FileSystemView view = FileSystemView.getFileSystemView();
// 获取文件对应的图标
Icon icon = view.getSystemIcon(file);
// 创建一个空白的Image对象
Image image = new ImageIcon().getImage();
// 创建一个MediaTracker对象
MediaTracker tracker = new MediaTracker(new JLabel());
// 将图标加载到Image对象中
try {
tracker.addImage(image, 0);
tracker.waitForAll();
image = iconToImage(icon);
tracker.removeImage(image, 0);
} catch (Exception e) {
e.printStackTrace();
}
try {
// 将Image对象转换为BufferedImage对象
BufferedImage bufferedImage = toBufferedImage(image);
File iconFile = new File("D:\\work\\project\\ieds-back-end\\target\\classes\\uploadFiles\\icon.jpg");
// 将BufferedImage对象保存到文件中
ImageIO.write(bufferedImage, "jpg", iconFile);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(1);
}
private static BufferedImage toBufferedImage(Image img) {
if (img instanceof BufferedImage) {
return (BufferedImage) img;
}
// 创建一个新的BufferedImage对象,并将图像绘制到该对象中
BufferedImage bimage = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = bimage.createGraphics();
g2d.drawImage(img, 0, 0, null);
g2d.dispose();
return bimage;
}
private static Image iconToImage(Icon icon) {
if (icon instanceof ImageIcon) {
return ((ImageIcon) icon).getImage();
} else {
int w = icon.getIconWidth();
int h = icon.getIconHeight();
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gd.getDefaultConfiguration();
BufferedImage image = gc.createCompatibleImage(w, h);
Graphics2D g2d = image.createGraphics();
icon.paintIcon(null, g2d, 0, 0);
g2d.dispose();
return image;
}
}