我一直在使用AVCaptureSession
捕获视频,当我使用kCVPixelFormatType_32BGRA
时,当我尝试使用kCVPixelFormatType_420YpCbCr8BiPlanarFullRange
并转换为UIImage
时它很好,但它是(黑色)没有颜色,我检查了一些SO问题并做了这样的转换:
CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
CVPixelBufferLockBaseAddress(imageBuffer, 0);
width = CVPixelBufferGetWidth(imageBuffer);
height = CVPixelBufferGetHeight(imageBuffer);
bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer);
uint8_t *baseAddress = (uint8_t*) CVPixelBufferGetBaseAddress(imageBuffer);
int bytes = height * bytesPerRow;
uint8_t *base = (uint8_t*) malloc(bytes);
memcpy(base,baseAddress,bytes);
CVPlanarPixelBufferInfo_YCbCrBiPlanar *bufferInfo = (CVPlanarPixelBufferInfo_YCbCrBiPlanar *)base;
NSUInteger yOffset = EndianU32_BtoN(bufferInfo->componentInfoY.offset);
NSUInteger yPitch = EndianU32_BtoN(bufferInfo->componentInfoY.rowBytes);
NSUInteger cbCrOffset = EndianU32_BtoN(bufferInfo->componentInfoCbCr.offset);
NSUInteger cbCrPitch = EndianU32_BtoN(bufferInfo->componentInfoCbCr.rowBytes);
uint8_t *rgbBuffer = (uint8_t*) malloc(width * height * 3);
uint8_t *yBuffer = base + yOffset;
uint8_t *cbCrBuffer = base + cbCrOffset;
for(int y = 0; y < height; y++)
{
uint8_t *rgbBufferLine = &rgbBuffer[y * width * 3];
uint8_t *yBufferLine = &yBuffer[y * yPitch];
uint8_t *cbCrBufferLine = &cbCrBuffer[(y >> 1) * cbCrPitch];
for(int x = 0; x < width; x++)
{
uint8_t y = yBufferLine[x];
uint8_t cb = cbCrBufferLine[x & ~1];
uint8_t cr = cbCrBufferLine[x | 1];
uint8_t *rgbOutput = &rgbBufferLine[x*3];
// from ITU-R BT.601, rounded to integers
rgbOutput[0] = (298 * (y - 16) + 409 * cr - 223) >> 8;
rgbOutput[1] = (298 * (y - 16) + 100 * cb + 208 * cr + 136) >> 8;
rgbOutput[2] = (298 * (y - 16) + 516 * cb - 277) >> 8;
}
}
// recording started, then get image and put it into the dictionnary
//CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef bitmapContext=CGBitmapContextCreate((uint8_t*) rgbBuffer,
width, height, 8, (width * 4), colorSpace,
kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst);
CGImageRef imageRef = CGBitmapContextCreateImage(bitmapContext);
CGColorSpaceRelease(colorSpace);
UIImage * newimage = [UIImage imageWithCGImage:imageRef];
if (gui_status.is_preview_on == true) {
dispatch_async(dispatch_get_main_queue(), ^{
if (newimage != nil) {
// Set image
}
});
}
free(base);
CGImageRelease(imageRef);
CGContextRelease(bitmapContext);
但它不起作用,有时会在上下文创建中崩溃。
'copy_read_only: vm_copy failed: status 1'