iphone - CGBitmapContextCreateImage - vm_copy 失败 - iPhone SDK

标签 iphone objective-c cgimage

我在我的 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,但我需要知道导致错误的原因,以免影响其他部分。

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

最佳答案

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

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

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

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

如果您 malloc 一 block 内存,将内存从 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);

关于iphone - CGBitmapContextCreateImage - vm_copy 失败 - iPhone SDK,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3367849/

相关文章:

iphone - plist 是为我的 iOS 应用程序存储多个应用程序内首选项的最佳方式吗?

iPhone - 具有富文本的 UITextField?

iphone 无法正确呈现网页

objective-c - 使用带格式的 NSString 定义方法

objective-c - 允许单击并拖动 View 以拖动窗口本身?

ios - IOS 中的索引路径嵌套 Tableview

iPhone - UIImage imageWithData 返回 nil

iphone - 单元测试时为 "Undefined symbols for architecture i386"

iphone - MKOverlay View 模糊

iphone - UIImage 第一次加载时卡顿