<Error>: CGBitmapContextCreateImage: invalid context 0x0. 解决方案

在使用AVAssetReader+AVAssetReaderTrackOutput处理视频并尝试将CMSampleBufferRef转换为CGImageRef时,遇到了 '<Error>: CGBitmapContextCreateImage: invalid context 0x0.' 的错误。错误通常由于高度或宽度为0导致。解决方案是在创建内容画布时添加逻辑判断,避免高度或宽度为0的情况,从而消除错误。参考了Stack Overflow和4byte.cn的相关讨论。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

阐述
最近研究 AVAssetReader+AVAssetReaderTrackOutput  用其写自己的视频播放类。编写CMSampleBufferRef转换 CGImageRef 的时候产生一些 Error,如下方:
<Error>: CGBitmapContextCreateImage: invalid context 0x0. If you want to see the backtrace, please set CG_CONTEXT_SHOW_BACKTRACE environmental variable.
<Error>: CGBitmapContextCreateImage: invalid context 0x0. This is a serious error. This application, or a library it uses, is using an invalid context  and is thereby contributing to an overall degradation of system stability and reliability. This notice is a courtesy: please fix this problem. It will become a fatal error in an upcoming update.

相关代码
- (CGImageRef)imageFromSampleBuffer:(CMSampleBufferRef)sampleBuffer {
    CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
    // Lock the base address of the pixel buffer
    CVPixelBufferLockBaseAddress(imageBuffer, 0);
    // Get the number of bytes per row for the pixel buffer
    size_t bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer);
    // Get the pixel buffer width and height
    size_t width = CVPixelBufferGetWidth(imageBuffer);
    size_t height = CVPixelBufferGetHeight(imageBuffer);
    //Generate image to edit
    unsigned char* pixel = (unsigned char *)CVPixelBufferGetBaseAddress(imageBuffer);
    CGColorSpaceRef colorSpace=CGColorSpaceCreateDeviceRGB();
    CGContextRef context=CGBitmapContextCreate(pixel, width, height, 8, bytesPerRow, colorSpace, kCGBitmapByteOrder32Little|kCGImageAlphaPremultipliedFirst);
    CGImageRef image = CGBitmapContextCreateImage(context);
    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);
    return image;
}

研讨
出现这类型错误,多半是创建内容画布的时候,height or width = 0, 因此在逻辑上添加判断(排除产生height or width = 0 的情况),可以消除这种错误。

资料

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值