0

I looked at the following post: Get pixel from the screen (screenshot) in Max OSX

and implemented the accepted answer as so:

Filename: screenshot.mm

#import <Foundation/Foundation.h>

#include <iostream>
#include <cstdint>
#include <cstdio>
#include <fstream>

void    captureScreen(void)
{
        CGImageRef image_ref = CGDisplayCreateImage(CGMainDisplayID());
        CGDataProviderRef provider = CGImageGetDataProvider(image_ref);
        CFDataRef dataref = CGDataProviderCopyData(provider);
        size_t width, height;
        width = CGImageGetWidth(image_ref);
        height = CGImageGetHeight(image_ref);
        size_t bpp = CGImageGetBitsPerPixel(image_ref) / 8;

        std::cout << bpp << " " << width << " " << height << std::endl;

        uint8 *pixels = (uint8*)malloc(width * height * bpp);
        memcpy(pixels, CFDataGetBytePtr(dataref), width * height * bpp);
        CFRelease(dataref);
        CGImageRelease(image_ref);

        std::ofstream file("image.ppm");

        file << "P6 " << width << " " << height << " " << "256" << "\n";

        for (size_t i = 0; i < height; i++)
        {
                for (size_t j = 0; j < width; j++)
                {
                        file << pixels[(j + j * i) * bpp + 0]
                                << pixels[(j + j * i) * bpp + 1]
                                << pixels[(j + j * i) * bpp + 2];
                }
                file << std::endl;
        }
}

int     main(void)
{
        NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

        captureScreen();

        [pool drain];
        return 0;
}

compiled with: clang++ -framework Foundation -framework CoreGraphics screenshot.mm

but when I view the screenshot it looks like this:

bugged screenshot

note: this is just part of the image since filesize was too large, but you get the idea

How can I correctly get the screenshot?

Theo Walton
  • 1,085
  • 9
  • 24
  • Do you really want the file in .ppm file format? Also, at the very least, you'll need to take the bytes-per-row of the image data into account. – Ken Thomases Jun 26 '18 at 02:26
  • i intend to use the image data internally but it was easier to debug by putting into .ppm format and looking at it – Theo Walton Jun 26 '18 at 02:58
  • Apple recommends that rather than trying to interpret an image's bitmap data, which can be in any of a lot of different formats, you should create a bitmap context in the format you want, draw the image into that, and then process that. See "NSBitmapImageRep: CoreGraphics impedance matching and performance notes" in the [10.6 AppKit release notes](https://developer.apple.com/library/archive/releasenotes/AppKit/RN-AppKitOlderNotes/#X10_6Notes). – Ken Thomases Jun 26 '18 at 03:30

0 Answers0