Using the System Clipboard for Images in Java

In Java 1.4, Sun added the DataFlavor imageFlavor to the java.awt.datatransfer package. This makes it possible to copy an image from a Snowbound application and paste it into a native application. To implement this in your application, use the basic class below to implement a transferable object which can contain image data in a form Java can process:
public class ClipImage implements Transferable, ClipboardOwner
{

private byte[] image;

public ClipImage(byte[] im)

{

image = im;

}

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

{

if (!isDataFlavorSupported(flavor))

throw new UnsupportedFlavorException(flavor);

return Toolkit.getDefaultToolkit().createImage(image);

}

public void lostOwnership(java.awt.datatransfer.Clipboard clip,

java.awt.datatransfer.Transferable tr)

{

return;

}

}

This class tells Java that the data stored in the byte array is of type imageFlavor and implements the necessary information for Java to make the native transfer to another application.

Next, you will need to write some code behind your copy action to store the data in the clipboard. Here is an example:

Clipboard clipboard = getToolkit().getSystemClipboard();

byte[] bytesTemp = new byte[2000000];

int stat = Simage.IMG_save_bitmap(bytesTemp, 13);

byte[] bytesFinal = new byte[stat];

System.arraycopy(bytesTemp, 0, bytesFinal, 0, stat);

ClipImage ci = new ClipImage(bytesFinal);

Clipboard.setContents(ci, null);

The above code snippet gets an instance of the System clipboard and allocates a byte array to save your current image to. It then saves that image as a JPEG. You should always use the JPEG format when saving to the clipboard. Finally, it trims the bytes in the array and stores them in the clipboard after creating a new clipboard image object.

There is a lot more you could add to this. For example, you could save cropped areas of the image or cut the image instead of copying it. However, this is a good beginning for using the image DataFlavor in Java 1.4.

Category:

Online Demo