Writing an image to disk

January 14, 2009

binary_photo1

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

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.

    .k

  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.

    -Ken

  3. rogerpadilla Says:

    I was looking for that some time ago.

    Thanks!


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


Leave a comment