Skip to content

Instantly share code, notes, and snippets.

@peterc
Created October 10, 2016 22:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save peterc/99991e4c66491d0e3b0e0c7734848cc0 to your computer and use it in GitHub Desktop.
Save peterc/99991e4c66491d0e3b0e0c7734848cc0 to your computer and use it in GitHub Desktop.
On OS X, take repeated screenshots / screengrabs of a certain window, scale, and save as RGBA constantly.
//
// main.m
// grabscreen
//
// Created by Peter Cooper on 09/10/2016.
// Copyright © 2016 Peter Cooper. All rights reserved.
//
#import <Cocoa/Cocoa.h>
#include <ApplicationServices/ApplicationServices.h>
#import <CoreGraphics/CoreGraphics.h>
#import <QuartzCore/QuartzCore.h>
int main(int argc, const char * argv[]) {
int destinationWidth = 1280;
int destinationHeight = 748;
NSString *path = @"/tmp/xbox.rgba";
NSURL *fileURL = [NSURL fileURLWithPath:path];
int windowId = 11367;
if (argc > 1)
windowId = atoi(argv[1]);
while(1) {
NSLog(@"grabbing frame");
CGImageRef image = CGWindowListCreateImage(CGRectNull, kCGWindowListOptionIncludingWindow, windowId, kCGWindowImageBoundsIgnoreFraming);
CGContextRef context = CGBitmapContextCreate(NULL, destinationWidth, destinationHeight, 8, 0, CGColorSpaceCreateDeviceRGB(), kCGImageAlphaPremultipliedFirst);
CGContextDrawImage(context, CGRectMake(0, 0, destinationWidth, destinationHeight), image);
char *data = CGBitmapContextGetData (context);
int size = destinationWidth * destinationHeight * 4;
// switch ARGB to RGBA (with full opacity)
for (int p = 0; p <= size; p += 4) {
data[p] = data[p + 1];
data[p + 1] = data[p + 2];
data[p + 2] = data[p + 3];
data[p + 3] = 0xFF;
}
NSData* d2 = [NSData dataWithBytes:(const void *)data length: size];
CGContextRelease(context);
[d2 writeToURL: fileURL atomically: NO];
CFRelease(image); // this took a while to realize, lol
[NSThread sleepForTimeInterval:0.05f];
}
return 0;
}
// odds and ends!
//NSString *path = [NSString stringWithFormat:@"%@/%@", NSHomeDirectory() , @"lincolnhack/a.png"];
// CFArrayRef windowList = CGWindowListCopyWindowInfo(kCGWindowListOptionOnScreenOnly, kCGNullWindowID);
// -- this will write a PNG instead (now unused)
//CGImageRef imgRef = CGBitmapContextCreateImage(context);
//CGImageDestinationRef dr = CGImageDestinationCreateWithURL((__bridge CFURLRef)fileURL, kUTTypePNG , 1, NULL);
//CGImageDestinationAddImage(dr, imgRef, NULL);
//CGImageDestinationFinalize(dr);
//CFRelease(dr);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment