首页 > 解决方案 > 使用目标 C++ 截取的屏幕截图有问题

问题描述

我查看了以下帖子:在 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

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

错误的屏幕截图

注意:这只是图像的一部分,因为文件太大,但你明白了

如何正确获取屏幕截图?

标签: objective-cscreenshotobjective-c++

解决方案


推荐阅读