Mike King
Mike King

Reputation: 21

How can I use Java to place a jpg file into the clipboard, so that it can be pasted into any document as an image?

I often have to add my signature to a document. The document can be of different kinds. My signature is stored as an image in signature.jpg.

I would like to write a Java program that automatically places this image in the clipboard, so that I only have to paste it into the document.

Upvotes: 2

Views: 890

Answers (2)

OscarRyz
OscarRyz

Reputation: 199294

You have to use me method: setContents from the Clipboard class.

Modified from: http://www.exampledepot.com/egs/java.awt.datatransfer/ToClipImg.html

import java.awt.*;
import java.awt.datatransfer.*;
public class LoadToClipboard {
    public static void main( String [] args ) {
        Toolkit tolkit = Toolkit.getDefaultToolkit();
        Clipboard clip = tolkit.getSystemClipboard();        
        clip.setContents( new ImageSelection( tolkit.getImage("StackOverflowLogo.png")) , null );
    }
}
class ImageSelection implements Transferable {
        private Image image;

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

        // Returns supported flavors
        public DataFlavor[] getTransferDataFlavors() {
            return new DataFlavor[]{DataFlavor.imageFlavor};
        }

        // Returns true if flavor is supported
        public boolean isDataFlavorSupported(DataFlavor flavor) {
            return DataFlavor.imageFlavor.equals(flavor);
        }

        // Returns image
        public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException {
            if (!DataFlavor.imageFlavor.equals(flavor)) {
                throw new UnsupportedFlavorException(flavor);
            }
            return image;
        }
    }

Upvotes: 2

Jeff
Jeff

Reputation: 21892

Take a look at the java.awt.datatransfer.* classes. You'll essentially have to develop an implementation of the java.awt.datatransfer.Transferable interface that will transfer an image to the clipboard.

Edit: Found a couple of tutorials that might help:

Upvotes: 1

Related Questions