上网找到的文章,基本上都是这两种方案,推荐使用第二种,第一种适合做窗口左上角小图标
import lombok.extern.slf4j.Slf4j;
import sun.awt.shell.ShellFolder;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.filechooser.FileSystemView;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
/**
* @author NPF
* @date 2020/10/27 15:53
*/
@Slf4j
public class Icon {
/**
* @param args
*/
public static void main(String[] args) throws FileNotFoundException {
Icon.getIcon1();
Icon.getIcon2();
}
/**
* 参考网址:https://blog.youkuaiyun.com/weixin_34023863/article/details/91560836
* 第一种形式获取icon,利用javax.swing中FileSystemView获取
* 缺点就是很小,很模糊
*/
public static void getIcon1(){
// --------------------------------------------
// 缺点就是很小,很模糊
File file1 = new File("C:\\Program Files (x86)\\KuGou2012\\KuGou.exe");
Image image = ((ImageIcon) FileSystemView.getFileSystemView().getSystemIcon(file1)).getImage();
int width = 10;
int height = 10;
BufferedImage bi = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
Graphics g = bi.getGraphics();
g.drawImage(image,0,0,width,height,null);
g.dispose();
File f = new File("D:\\KuGou.exe11.png");
try {
ImageIO.write(bi, "png", f);
} catch (IOException e) {
log.error("写png文件失败",e);
}
}
/**
* 推荐使用
* 参考网址:https://zhidao.baidu.com/question/317417746.html
* 第二种形式获取icon,利用通过awt.shellFolder获取图标
* 获取的32*32 比较清晰,可以使用
*/
public static void getIcon2() throws FileNotFoundException {
File file = new File("C:\\Program Files (x86)\\KuGou2012\\KuGou.exe");
// 图标保存地址
OutputStream inStream = new FileOutputStream(new File("D:\\KuGou.exe_64.png"));
try {
// 通过awt.shellFolder获取图标 默认为32 *32
ShellFolder shellFolder = ShellFolder.getShellFolder(file);
ImageIcon icon = new ImageIcon(shellFolder.getIcon(true));
BufferedImage imgIcon = (BufferedImage) icon.getImage();
// 调整icon图标大小,放大后会模糊
imgIcon = resize(imgIcon,64,64);
ImageIO.write(imgIcon, "png", inStream);
inStream.flush();
inStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 调整大小
* @param img
* @param newW
* @param newH
* @return
*/
public static BufferedImage resize(BufferedImage img, int newW, int newH) {
int w = img.getWidth();
int h = img.getHeight();
BufferedImage dimg = new BufferedImage(newW, newH, img.getType());
Graphics2D g = dimg.createGraphics();
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.drawImage(img, 0, 0, newW, newH, 0, 0, w, h, null);
g.dispose();
return dimg;
}
}