Search code examples
c++ccore-graphicsmacos-carbon

Putting a CGImageRef on the clipboard


I'm trying to copy a CGImageRef to the clipboard pasteboard. I found a function that claims it should do this by creating a destination from (zero sized), adding the image to the destination, finalizing, then PasteboardPutItemFlavor the ref into the clipboard.

However it doesn't work, so two questions:

  1. Is this the correct way to go about this? (ie, is there just a small bug, or am I doing it wrong?)

  2. What type should I make the destination? The source had it as TIFF, but word doesn't seem to know how to deal with that, I changed it to PICT, which at least gave me the "paste" option, but then said it was too big...

Code:

void copyCGImageRefToPasteboard(CGImageRef ref)
{
    OSStatus err = noErr;
    PasteboardRef theClipboard;

    err = PasteboardCreate( kPasteboardClipboard, &theClipboard );
    err = PasteboardClear( theClipboard );// 1

    CFMutableDataRef url = CFDataCreateMutable(kCFAllocatorDefault, 0);

    CFStringRef type = kUTTypePICT;
    size_t count = 1;
    CFDictionaryRef options = NULL;
    CGImageDestinationRef dest = CGImageDestinationCreateWithData(url, type, count, options);
    CGImageDestinationAddImage(dest, ref, NULL);
    CGImageDestinationFinalize(dest);

    err = PasteboardPutItemFlavor( theClipboard, (PasteboardItemID)1, type, url, 0 );
}

Solution

  • Ok, I'm answering my own question here, but here's what I've found:

    Apple wants you to use PDF for pasteboards. So if you swap out Pict with PDF, it pretty muc just works. However, MS Word (what I was testing with) only started to allow pasting of PDF in the newest version (Which I don't have).

    So, that's the solution, use PDF, and require Word 2008.