Search code examples
javaclipboardtransferable

Get DataFlavor[] from a custom DataFlavor


I want created a program that copies images from a folder into the clipboard, but the images become black.

After doing some research, I found this: Clipboard copy from outlook always has black background set when retrieved as image from Java clipboard object There he says using image\x-emf fixes the problem. But I can't figure out how to get the TransferData from " new DataFlavor("image/x-emf") "

package Package1;

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

import javax.swing.ImageIcon;

/** Transferable image */
public class imageSelection implements Transferable {
    private Image image;

    /** Creates a transferable object that is an image. 
     *  <p>imageSelection(Image)
     * */
    public imageSelection(Image image) {
        this.image = image;
    }

    public DataFlavor[] getTransferDataFlavors() {
        //DataFlavor[] BlackBackgroundImage = new DataFlavor[] { DataFlavor.imageFlavor }; // <--- Gives me a black background instead of transparent

        DataFlavor[] transferData = null;
        try {
            transferData =  new DataFlavor("image/x-emf"); // <---- How to get TransferData from this
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            error.displayError(e.getStackTrace(), "Error creating DataFlavor (mime type: image/x-emf)");
        }
        return transferData;
    }

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

Method call (where emojiLocation is the path to the image):

imageSelection imgSel = new imageSelection(new ImageIcon(emojiLocation).getImage());

Thanks in advance!



Solution

  • Solution: return new DataFlavor[] { transferData } Sorry for missing something so obvious. This didn't lead me to other problems tho and didn't allow me to achieve a transparent image, so I made a new question in hope to solve this: Set clipboard to transparent image