I'm trying to copy an image with a transparent background to the clipboard, but when I paste it in Photoshop (for an example) the background comes out as black. This is my code:
import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFrame;
public class CopyExample
extends JFrame
implements ActionListener {
public static void main(String[] args) {
new CopyExample();
}
public CopyExample() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(200, 200);
JButton button = new JButton("Copy");
button.addActionListener(this);
add(button);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
final BufferedImage image = new BufferedImage(
200, 200, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = image.createGraphics();
g2.setComposite(AlphaComposite.Clear);
g2.fillRect(0, 0, 200, 200);
g2.setComposite(AlphaComposite.SrcOver);
g2.setColor(Color.GREEN);
g2.fillRect(50, 50, 100, 100);
g2.dispose();
Transferable transf = new ImageTransferable(image);
Toolkit.getDefaultToolkit()
.getSystemClipboard()
.setContents(transf, null);
// try {
// ImageIO.write(image, "png", new File("out.png"));
// } catch(IOException ex) { ex.printStackTrace(); }
}
}
class ImageTransferable implements Transferable {
private Image image;
public ImageTransferable(Image image) {
this.image = image;
}
public DataFlavor[] getTransferDataFlavors() {
return new DataFlavor[] {
DataFlavor.imageFlavor
};
}
public boolean isDataFlavorSupported(DataFlavor flavor) {
return flavor.match(DataFlavor.imageFlavor);
}
public Object getTransferData(DataFlavor flavor)
throws UnsupportedFlavorException, IOException {
return image;
}
}
I'm creating a BufferedImage and clears the background first, just to be sure. And then I copy it to the clipboard. I also tried to save it to a PNG file and that works fine. Any ideas?