Copy and paste image to and from System Clipboard

 
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;

import javax.swing.ImageIcon;

public class Main {
  public static void main(String[] argv) throws Exception {

    ImageSelection imgSel = new ImageSelection(new ImageIcon("a.png").getImage());
    Toolkit.getDefaultToolkit().getSystemClipboard().setContents(imgSel, null);

    Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard()
        .getContents(null);

    if (t != null && t.isDataFlavorSupported(DataFlavor.imageFlavor)) {
      Image img = (Image) t.getTransferData(DataFlavor.imageFlavor);
    }

  }
}

class ImageSelection implements Transferable {
  private Image image;

  public ImageSelection(Image image) {
    this.image = image;
  }

  public DataFlavor[] getTransferDataFlavors() {
    return new DataFlavor[] { DataFlavor.imageFlavor };
  }

  public boolean isDataFlavorSupported(DataFlavor flavor) {
    return DataFlavor.imageFlavor.equals(flavor);
  }

  public Object getTransferData(DataFlavor flavor)
      throws UnsupportedFlavorException, IOException {
    if (!DataFlavor.imageFlavor.equals(flavor)) {
      throw new UnsupportedFlavorException(flavor);
    }
    return image;
  }
}
  
Home 
  Java Book 
    Runnable examples  

System:
  1. Copy and paste string to and from System Clipboard
  2. Copy and paste image to and from System Clipboard
  3. Alert when Losting Clipboard owner
  4. System beeper
  5. Beep by printing the ASCII Bell character to the console
  6. Total amount of memory in Java virtual machine
  7. Maximum amount of memory in Java virtual machine
  8. Free amount of memory in Java Virtual Machine
  9. Environment variables