Search code examples
cocoaopenglscreenshotcgimage

How do I select an area of the screen and save it as a CGimage or CIImage?


I'm creating an application to capture a small area of the screen and compare it to a library of images saved to disk. I wrote a similar application a few years ago in .net and used bitblt and the WINAPI. Performance is really important and I don't mind delving into openGL if it would make a difference with performance.


Solution

  • You could use some code like this:

    -(NSImage*)captureImageFromRect:(NSRect)captureRect
    {
        NSImage *resultingImage = nil;
        CGImageRef image;
        CGWindowID  windowID = (CGWindowID)[[self window] windowNum];
        image = CGWindowListCreateImage(NSRectToCGRect(captureRect), kCGWindowListOptionIncludingWindow|kCGWindowListOptionOnScreenBelowWindow, windowID, kCGWindowImageDefault);
        resultingImage = [[NSImage alloc] initWithCGImage:image size:NSZeroSize];
        CGImageRelease(image);
        return [resultingImage autorelease];
    }