使用目标C ++拍摄的屏幕截图有很多错误

时间:2018-06-25 22:14:19

标签: objective-c screenshot objective-c++

我看了以下帖子:Get pixel from the screen (screenshot) in Max OSX

并按以下方式实施了接受的答案:

文件名: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;
}

编译为:clang++ -framework Foundation -framework CoreGraphics screenshot.mm

但是当我查看屏幕截图时,它看起来像这样:

bugged screenshot

注意:这只是图像的一部分,因为文件大小太大,但是您知道了

如何正确获取屏幕截图?

0 个答案:

没有答案