Java: How to get an image off the system clipboard

Java clipboard FAQ: How do I get an image off the clipboard using Java?

I guess timing is everything ... I just received this Java clipboard question as I am working on a Java Swing application that does a lot of graphics and image work, so I have a little source code here I can share.

Java clipboard image method

Here's the source code for a Java method that I use to retrieve an image from the system clipboard. This method can help handle the "paste" portion of a copy and paste operation in your Java application.

/**
 * 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();
    }
  }
  else
  {
    System.err.println("getImageFromClipboard: That wasn't an image!");
  }
  return null;
}

As you can see, there is a lot of boilerplate exception handling code wrapped around two or three lines of useful Java clipboard code. If you want to shrink that method down and just throw an exception, the following code should work. (I didn't test it, I just copied and pasted the code above, and removed all the exception handling code).

public Image getImageFromClipboard()
throws Exception
{
  Transferable transferable = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
  if (transferable != null && transferable.isDataFlavorSupported(DataFlavor.imageFlavor))
  {
    return (Image) transferable.getTransferData(DataFlavor.imageFlavor);
  }
  else
  {
    return null;
  }
}

Java clipboard - summary

I hope this Java clipboard image handling code is helpful to you. This method can help handle the "paste" portion of a copy and paste operation.

On a related note, here's a quick link to a tutorial that shows how to place text on the clipboard using Java.