为什么我不能将缓冲图像投射到可传输对象中以将其发送到剪贴板?

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

我正在尝试将 bufferedImage 保存到我系统的剪贴板,基本上我的程序对一个区域进行屏幕截图并将其保存为 PNG,但现在我希望它能够将该图像发送到剪贴板也是,

我试过 Toolkit.getDefaultToolkit().getSystemClipboard().setContents( (Transferable) myImage, null);

Eclipse 希望我将缓冲的 myImage 图像转换为可传输图像,但这是不允许的,而且我在 Whosebug 上查看的代码与我的整个程序一样长,我未能正确使用它,所以我不确定什么是可转移的以及如何从我的缓冲图像中制作一个,有人可以解释一下吗?

您不能将 BufferedImage 转换为 Transferable(因为它们是不同的类型)。

但是,您可以像这样轻松地将图像包裹在 Transferable 中:

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