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