Hi Guys,
I am new to developing on the Mac platform. I am trying to take a screenshot using OpenGL and then paste the resulting image to the paste board. My code runs but nothing ends up in the paste board. Could someone possibly point me in the right direction? I can't figure out why the following code wont work. Any advice would be greatly appreciated! Thanks!
I am new to developing on the Mac platform. I am trying to take a screenshot using OpenGL and then paste the resulting image to the paste board. My code runs but nothing ends up in the paste board. Could someone possibly point me in the right direction? I can't figure out why the following code wont work. Any advice would be greatly appreciated! Thanks!
Code:
CGDirectDisplayID display = CGMainDisplayID();
CGRect srcRect;
srcRect.origin.x = 0;
srcRect.origin.y = 0;
srcRect.size.height = 800;
srcRect.size.width = 600;
//grab screenshot via opengl and return image as CGImageRef
CGImageRef ref= grabViaOpenGL(display, srcRect);
size_t pixelsWide = CGImageGetWidth(ref);
size_t pixelsHigh = CGImageGetHeight(ref);
int bitmapBytesPerRow = (pixelsWide * 4);
int bitmapByteCount = (bitmapBytesPerRow * pixelsHigh);
//convert CGImageRef to CGContextRef
CGContextRef cgctx = CreateARGBBitmapContext(ref);
// Get image width, height. We'll use the entire image.
size_t w = CGImageGetWidth(ref);
size_t h = CGImageGetHeight(ref);
CGRect rect = {{0,0},{w,h}};
// Draw the image to the bitmap context. Once we draw, the memory
// allocated for the context for rendering will then contain the
// raw image data in the specified color space.
CGContextDrawImage(cgctx, rect, ref);
// Now we can get a pointer to the image data associated with the bitmap
// context.
void *data = CGBitmapContextGetData (cgctx);
if (data != NULL)
{
OSStatus err = noErr;
PasteboardRef theClipboard;
CFDataRef imageData = NULL;
//create pasteboard
err = PasteboardCreate( kPasteboardClipboard, &theClipboard );
err = PasteboardClear( theClipboard );// 1
PasteboardSynchronize( theClipboard );// 2
//create CFDataRef from image
imageData = CFDataCreate( kCFAllocatorDefault, (UInt8 *)data, bitmapByteCount);
//paste image to clipboard in tiff format
err = PasteboardPutItemFlavor( theClipboard, (PasteboardItemID)1, CFSTR("public.tiff"), imageData, 0 );
CFRelease( imageData );
}