Search code examples
javaclipboardbufferedimagetransferable

Why can't I cast a buffered image into a transferrable object to send it to the clipboard?


I'm trying to save a bufferedImage to my system's clipboard, basically my program makes a screencapture of an area and saves it as a PNG, but now I'd like it to be able to send that image to the clipboard too,

I've tried with Toolkit.getDefaultToolkit().getSystemClipboard().setContents( (Transferable) myImage, null);

Eclipse wants me to cast my buffered myImage image into a transferable, yet it's not allowed, and the code I've looked at on stackOverflow on the matter is about as long as my whole program, I failed to use it properly, so I'm not sure what a transferable is and how could I make one from my Buffered Image, would someone explain?


Solution

  • You can't cast a BufferedImage to a Transferable (as they are distinct types).

    However, you can easily wrap your image in a Transferable like this:

    Toolkit.getDefaultToolkit()
            .getSystemClipboard()
            .setContents(new ImageTransferable(myImage), null);
    
    static final class ImageTransferable {
        final BufferedImage image;
    
        public ImageTransferable(final BufferedImage image) {
            this.image = image;
        }
    
        @Override
        public DataFlavor[] getTransferDataFlavors() {
            return new DataFlavor[] {DataFlavor.imageFlavor};
        }
    
        @Override
        public boolean isDataFlavorSupported(final DataFlavor flavor) {
            return DataFlavor.imageFlavor.equals(flavor);
        }
    
        @Override
        public Object getTransferData(final DataFlavor flavor) throws UnsupportedFlavorException, IOException {
            if (isDataFlavorSupported(flavor)) {
                return image;
            }
    
            throw new UnsupportedFlavorException(flavor);
        }
    };