【问题标题】:CoreGraphics CGImage from CGDisplayStream weird colors来自 CGDisplayStream 的 CoreGraphics CGImage 奇怪的颜色
【发布时间】:2018-10-15 08:58:26
【问题描述】:

我目前是第一次使用 CoreGraphics API(主要是 C++ 代码),我尝试从 CGDisplayStream 中获取缩略图(或“屏幕截图”),除了颜色之外效果很好。

我使用CGDisplayStreamCreate()(documentation) 创建CGDisplayStream,并使用处理程序块(see this) 内的IOSurfaceRef 创建CGImageRef。 这是我的测试代码:

CVPixelBufferRef p_buffer = NULL;
CFDictionaryRef attributes = CFDictionaryCreate(NULL, NULL, NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);

CVReturn ret = CVPixelBufferCreateWithIOSurface(kCFAllocatorDefault, surface, attributes, &p_buffer);

CVPixelBufferLockBaseAddress(p_buffer, kCVPixelBufferLock_ReadOnly);

void* baseAddr = CVPixelBufferGetBaseAddress(p_buffer);
size_t width = CVPixelBufferGetWidth(p_buffer);
size_t height = CVPixelBufferGetHeight(p_buffer);

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

CGContextRef cgContext = CGBitmapContextCreate(baseAddr, width, height, 8, CVPixelBufferGetBytesPerRow(p_buffer), colorSpace, kCGImageAlphaNoneSkipLast);

CGImageRef img = CGBitmapContextCreateImage(cgContext);

创建 CGDisplayStream 的调用如下所示:

CGDisplayStreamCreate(CGMainDisplayID(), 1920, 1080, 'BGRA', NULL,
                     ^(CGDisplayStreamFrameStatus status, uint64_t time, IOSurfaceRef surface, CGDisplayStreamUpdateRef metadata){ //above handler snipped is in here });

我怀疑 pixelFormat (see this) 或 CGColorSpace 产生了我奇怪的输出,但我不确定。除了盲目猜测一些随机设置外,我也不知道我现在能做什么。 也许有人可以给我一个线索?

这是我的输出与“真实”屏幕截图的对比。

【问题讨论】:

    标签: c++ core-graphics screenshot cgimage


    【解决方案1】:

    终于找到解决方案here:

    我换行了

    CGContextRef cgContext = CGBitmapContextCreate(baseAddr, width, height, 8, CVPixelBufferGetBytesPerRow(p_buffer), colorSpace, kCGImageAlphaNoneSkipLast);
    

    到

    CGContextRef cgContext = CGBitmapContextCreate(baseAddr, width, height, 8, CVPixelBufferGetBytesPerRow(p_buffer), colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipFirst);
    

    现在它工作正常。

    我仍然不太清楚为什么这是一个解决方案。我想此时需要对图像格式和颜色有更深入的了解。

    【讨论】:

      猜你喜欢
      • 2021-04-28
      • 1970-01-01
      • 2011-08-22
      • 1970-01-01
      • 1970-01-01
      • 2018-02-22
      • 1970-01-01
      • 1970-01-01
      • 2016-08-26
      相关资源
      最近更新 更多