I have got some problem resulting from my unaccustomedness with swing/awt.
Is there any chance for me to convert an Icon to ImageIcon.
Problem is I need the ImageData object as I want to do further work with
the icon. But
FileSystemView.getFileSystemView().getSystemIcon(file);
only gives me Icon objects ... most of the time these are instances of
ImageIcon so instanceof checking and casting helps 99 out of 100 times.
Though sometimes especially on Mac it returns native implementations and
it would be nice to also get the image data from these Icon Objects.
Anyone have expereince with this and could give me a hint what I could do?
Christian
Create a BufferedImage whose width and height are the Icon's return
values for getIconWidth and getIconHeight. Then call the Icon's
paintIcon with some AWT component, the BufferedImage's Graphics object,
and two zeros.
The AWT component's background and foreground color settings may
influence the results, but you should now have a BufferedImage with a
rasterized version of the icon.
Since this uses solely the three methods specified in the Icon
interface, it should work no matter what Icon is used, or how that Icon
happens to be implemented.
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 g = image.createGraphics();
icon.paintIcon(null, g, 0, 0);
g.dispose();
return image;
}
}
Bye.
--
Real Gagnon from Quebec, Canada
* Java, Javascript, VBScript and PowerBuilder code snippets
* http://www.rgagnon.com/howto.html
* http://www.rgagnon.com/bigindex.html