Created
November 29, 2019 03:01
-
-
Save sipadan2003/c47df92379fba8f61882022e06c6ab56 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.awt.Color; | |
import java.awt.Graphics; | |
import java.awt.MediaTracker; | |
import java.awt.image.BufferedImage; | |
import java.io.File; | |
import javax.imageio.ImageIO; | |
import javax.swing.ImageIcon; | |
import javax.swing.filechooser.FileSystemView; | |
import sun.awt.shell.ShellFolder; | |
public class SystemIconGetter { | |
public static void main(String[] args) { | |
try{ | |
if(args.length == 1){ | |
final File file = new File(args[0]); | |
saveIconImage(file, 16); | |
}else if(args.length == 2){ | |
final int size = "32".equals(args[1]) ? 32: 16; | |
final File file = new File(args[0]); | |
saveIconImage(file, size); | |
}else{ | |
System.err.println(Main.class.getName()+" <path to file> [size]"); | |
System.err.println(" size: 16(default) or 32"); | |
System.exit(1); | |
} | |
}catch(Exception ex){ | |
ex.printStackTrace(); | |
System.exit(2); | |
} | |
} | |
private static void saveIconImage(File file, int size) throws Exception { | |
//OSからファイルのアイコンイメージを取得 | |
final ImageIcon icon = (size==16) ? | |
(ImageIcon)FileSystemView.getFileSystemView().getSystemIcon(file) : | |
new ImageIcon(ShellFolder.getShellFolder(file).getIcon(true)); | |
//イメージのロードが完了するまで待機 | |
while(icon.getImageLoadStatus() != MediaTracker.COMPLETE){ | |
System.out.println("Waiting for loading image.: status="+icon.getImageLoadStatus()); | |
Thread.sleep(100); | |
} | |
//イメージのサイズを取得 | |
final int width = icon.getIconWidth(); | |
final int height = icon.getIconHeight(); | |
System.out.println("icon size=("+width+", "+height+")"); | |
//BufferdImageを生成し、データを書き込む | |
final BufferedImage bimage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); | |
final Graphics g = bimage.getGraphics(); | |
g.setColor(new Color(255, 255, 255, 255)); | |
g.fillRect(0, 0, width, height); | |
g.drawImage(icon.getImage(), 0, 0, null); | |
g.dispose(); | |
// | |
final File outputFile = new File("output.gif"); | |
final boolean b = ImageIO.write(bimage, "gif", outputFile); | |
System.out.println("Write image: path="+outputFile.getAbsolutePath()+", result="+b); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment