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(
// 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();

// 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");
ImageIO.write(image, "png", file);

4 Responses to “Writing an image to disk”

  1. Harald K. Says:

    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.


  2. Ken Says:

    Hi Harald,

    “NSImage://[image name]” is some magic that Apple came up with for accessing system images on the Mac from Java – pretty nifty.


  3. rogerpadilla Says:

    I was looking for that some time ago.


  4. […] at Exploding Pixels writes about how he managed to write an image to disk, accessing it through the Mac OS NSImage:// […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: