How to paste an image into a Java Swing application

I've been doing a lot of work with Java and images on MacOS lately, and I thought I'd share a Java method I use to get an image off the clipboard. I won't get into the details of working with an Image or a BufferedImage in this tutorial, but I will show you how to get the Image off the clipboard. (I will share a lot more about how to work with images in Java/Swing applications in other tutorials.)

Here's the Java source code for my method that gets an Image from the system clipboard:

/**
 * Get an image off the system clipboard.
 * @return Returns an Image if successful; otherwise returns null.
 */
public Image getImageFromClipboard()
{
  Transferable transferable = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
  if (transferable != null && transferable.isDataFlavorSupported(DataFlavor.imageFlavor))
  {
    try
    {
      return (Image) transferable.getTransferData(DataFlavor.imageFlavor);
    }
    catch (UnsupportedFlavorException e)
    {
      // handle this as desired
      e.printStackTrace();
    }
    catch (IOException e)
    {
      // handle this as desired
      e.printStackTrace();
    }
  }
  return null;
}

As you can see from the comments in the code, that method catches any exceptions that may occur, and then returns a null reference if the method fails for some reason.

I've tested this on Mac OS X 10.5.7 and Java 1.5.x over the last few days, and it works fine for me. You might think that there's a little limit in there where I'm explicitly looking for a DataFlavor.imageFlavor, but in practice this isn't a problem. I'm expecting an image to be on the clipboard when this method is called, so if I get a null when I call this method, I can be pretty sure there wasn't an image on the clipboard to get.

How I call this method

For example, in one of my Java programs I call this getImageFromClipboard method like this:

public void doPasteAction()
{
  originalImage = getImageFromClipboard();
  
  // you might want to handle this better in your program
  if (originalImage == null) return;
  
  // success, got the image. 
  // more code here to do the drawing ...
}

As you can see, I call the getImageFromClipboard from a method named doPasteAction, so in my code I am expecting an image to be on the clipboard, but if there isn't one, no big deal, I just bail out of this method.