10

我在我的 iPhone 应用程序中使用 CGBitmapContextCreateImage 时遇到问题。

我正在使用 AV Foundation Framework 使用这种方法来抓取相机帧:

- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection {
    CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
    CVPixelBufferLockBaseAddress(imageBuffer,0);
    uint8_t *baseAddress = (uint8_t *)CVPixelBufferGetBaseAddress(imageBuffer);
    size_t bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer);
    size_t width = CVPixelBufferGetWidth(imageBuffer);
    size_t height = CVPixelBufferGetHeight(imageBuffer);
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef newContext = CGBitmapContextCreate(baseAddress, width, height, 8, bytesPerRow, colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst);
    CGImageRef newImage = CGBitmapContextCreateImage(newContext);
    CVPixelBufferUnlockBaseAddress(imageBuffer,0);
    CGContextRelease(newContext);
    CGColorSpaceRelease(colorSpace);

    UIImage *image= [UIImage imageWithCGImage:newImage scale:1.0 orientation:UIImageOrientationRight];
    self.imageView.image = image;

    CGImageRelease(newImage);

} 

但是,我在调试控制台运行时看到一个错误:

<Error>: CGDataProviderCreateWithCopyOfData: vm_copy failed: status 2.

有没有人见过这个?通过注释掉行,我将问题范围缩小到:

CGImageRef newImage = CGBitmapContextCreateImage(newContext);

但我不知道如何摆脱它。从功能上讲,它工作得很好。很明显,正在创建 CGImage,但我需要知道是什么导致了错误,所以它不会影响其他部分。

非常感谢。任何帮助/建议都会很棒!布雷特

4

1 回答 1

11

免责声明:这是纯粹的猜测。不再。

vm_copy()是一个内核调用,用于将虚拟内存从一个地方复制到另一个地方(手册页)。

你得到的返回值是KERN_PROTECTION_FAILURE,“源区域被保护不被读取,或者目标区域被保护不被写入。”

所以由于某种原因 CGDataProviderCreateWithCopyOfData 调用它来复制一些内存,但失败了。也许它只是首先尝试将 vm_copy 作为一种快速方法,然后再使用一种较慢的方法(因为您说一切正常)。

如果您malloc有一大块内存,请将内存从 baseAddress 存储到您自己的内存中,然后使用它来创建图像,警告就会消失。所以:

uint8_t *tmp = (uint8_t *)CVPixelBufferGetBaseAddress(imageBuffer);
int bytes = ... // determine number of bytes from height * bytesperrow
uint8_t *baseAddress = malloc(bytes);
memcpy(baseAddress,tmp,bytes);

// unlock the memory, do other stuff, but don't forget:
free(baseAddress);
于 2010-07-30T01:07:05.243 回答