我正在尝试从 CGImage 创建 CVPixelBufferRef 所以这里是方法:
- (CVPixelBufferRef) pixelBufferFromCGImage: (CGImageRef) image
{
CGImageRetain(image);
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], kCVPixelBufferCGImageCompatibilityKey,
[NSNumber numberWithBool:YES], kCVPixelBufferCGBitmapContextCompatibilityKey,
nil];
CVPixelBufferRef pxbuffer = NULL;
CVPixelBufferCreate(kCFAllocatorDefault, CGImageGetWidth(image),
CGImageGetHeight(image), kCVPixelFormatType_32ARGB, (CFDictionaryRef) options,
&pxbuffer);
CVPixelBufferLockBaseAddress(pxbuffer, 0);
void *pxdata = CVPixelBufferGetBaseAddress(pxbuffer);
CGColorSpaceRef rgbColorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(pxdata, CGImageGetWidth(image),
CGImageGetHeight(image), 8, 4*CGImageGetWidth(image), rgbColorSpace,
kCGImageAlphaNoneSkipFirst);
CGContextRetain(context);
CGContextConcatCTM(context, CGAffineTransformMakeRotation(0));
CGContextDrawImage(context, CGRectMake(0, 0, CGImageGetWidth(image),
CGImageGetHeight(image)), image);
CGColorSpaceRelease(rgbColorSpace);
CGContextRelease(context);
CVPixelBufferUnlockBaseAddress(pxbuffer, 0);
CGContextRelease(context);
CGImageRelease(image);
return pxbuffer;
}
我经常调用这个方法,它用于生成视频帧,25fps。这在大多数情况下都可以正常工作,但在某些时候它会在这行代码上崩溃:
CGContextDrawImage(context, CGRectMake(0, 0, CGImageGetWidth(image),
CGImageGetHeight(image)), image);
我已经测试了内存使用和内存泄漏,一切都很好,但仍然会出现崩溃。
崩溃堆栈:线程 6 崩溃:
0 ImageIO 0x39270806 CGImageReadGetBytesAtOffset + 34
1 ImageIO 0x392707d6 CGImageReadSessionGetBytes + 22
2 ImageIO 0x39280c3c fill_input_buffer + 148
3 ImageIO 0x3928003a read_markers + 154
4 ImageIO 0x3927fd82 consume_markers + 34
5 ImageIO 0x3927fbd2 _cg_jpeg_consume_input + 66
6 ImageIO 0x3927fb62 _cg_jpeg_read_header + 38
7 ImageIO 0x39292782 copyImageBlockSetJPEG + 2346
8 ImageIO 0x3928953e ImageProviderCopyImageBlockSetCallback + 510
9 CoreGraphics 0x38e0b9d6 CGImageProviderCopyImageBlockSetWithOptions + 158
10 CoreGraphics 0x38e0b66a img_blocks_create + 370
11 CoreGraphics 0x38e07a98 img_data_lock + 1488
12 CoreGraphics 0x38e06d2a CGSImageDataLock + 126