Writing an image to disk
January 14, 2009
I recently wanted to get at some Apple artwork that is exposed in Java via a URL-esque mechanism (see the code below). I knew the artwork was on my machine somewhere, I just didn’t know where.
I decided that it would be easiest to whip up a little code to write the image to disk after it had been loaded by the Mac JVM. Here’s that code snippet, nice and simple, but valuable enough that I thought it was worth sharing:
// load the image.
ImageIcon icon = new ImageIcon(Toolkit.getDefaultToolkit().getImage(
"NSImage://NSPreferencesGeneral"));
// create a BufferedImage, which implements RenderedImage, to draw the icon's
// image into.
BufferedImage image = new BufferedImage(
icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_ARGB);
// create a graphics context from the BufferedImage and draw the icon's image into it.
Graphics g = image.createGraphics();
g.drawImage(icon.getImage(),0,0,null);
g.dispose();
// create a file to write the image to (make sure it exists), then use the ImageIO class
// to write the RenderedImage to disk as a PNG file.
File file = new File("/Users/kenorr/Desktop/myImageFile.png");
file.createNewFile();
ImageIO.write(image, "png", file);
January 14, 2009 at 9:49 am
Hi Ken,
Is the “NSImage://NSPreferencesGeneral” URL syntax a documented way of getting image artwork on OS X or some magic you made? Cool, never seen that before. :-)
Another thing, you should probably check the return value of file.createNewFile();, if you want it to have any effect. As is, the code will just overwrite the old image.
.k
January 14, 2009 at 11:46 am
Hi Harald,
“NSImage://[image name]” is some magic that Apple came up with for accessing system images on the Mac from Java – pretty nifty.
-Ken
January 14, 2009 at 8:25 pm
I was looking for that some time ago.
Thanks!
January 18, 2009 at 3:03 am
[...] at Exploding Pixels writes about how he managed to write an image to disk, accessing it through the Mac OS NSImage:// [...]