UIImage转CVPixelBuffer
- + (CVPixelBufferRef)pixelBufferFromCGImage:(CGImageRef)image {
- NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
- [NSNumber numberWithBool:true], kCVPixelBufferCGImageCompatibilityKey,
- [NSNumber numberWithBool:true], kCVPixelBufferCGBitmapContextCompatibilityKey, nil];
- CVPixelBufferRef pxbuffer = NULL;
- size_t width = CGImageGetWidth(image);
- size_t height = CGImageGetHeight(image);
- CVReturn status = CVPixelBufferCreate(kCFAllocatorDefault, width, height, kCVPixelFormatType_32BGRA, (__bridge CFDictionaryRef)options, &pxbuffer);
- if (status != kCVReturnSuccess) {
- NSLog(@"CVPixelBufferCreate Fail");
- }
- CVPixelBufferLockBaseAddress(pxbuffer, 0);
- void *pxdata = CVPixelBufferGetBaseAddress(pxbuffer);
- CGColorSpaceRef rgbColorSpace = CGColorSpaceCreateDeviceRGB();
- CGContextRef context = CGBitmapContextCreate(pxdata, width, height, 8, CVPixelBufferGetBytesPerRow(pxbuffer), rgbColorSpace, (CGBitmapInfo)kCGImageAlphaNoneSkipFirst);
-
- CGContextDrawImage(context, CGRectMake(0, 0, width, height), image);
- CVPixelBufferUnlockBaseAddress(pxbuffer, 0);
-
- CGColorSpaceRelease(rgbColorSpace);
- CGContextRelease(context);
-
- return pxbuffer;
- }
CVPixelBuffer转UIImage
- + (UIImage *)imageFromPixelBuffer:(CVPixelBufferRef)pixelBuffer {
- CVImageBufferRef imageBuffer = pixelBuffer;
-
- CVPixelBufferLockBaseAddress(imageBuffer, 0);
- void *baseAddress = CVPixelBufferGetBaseAddress(imageBuffer);
- size_t width = CVPixelBufferGetWidth(imageBuffer);
- size_t height = CVPixelBufferGetHeight(imageBuffer);
- size_t bufferSize = CVPixelBufferGetDataSize(imageBuffer);
- size_t bytesPerRow = CVPixelBufferGetBytesPerRowOfPlane(imageBuffer, 0);
-
- CGColorSpaceRef rgbColorSpace = CGColorSpaceCreateDeviceRGB();
- CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, baseAddress, bufferSize, NULL);
-
- CGImageRef cgImage = CGImageCreate(width, height, 8, 32, bytesPerRow, rgbColorSpace, kCGImageAlphaNoneSkipFirst | kCGBitmapByteOrderDefault, provider, NULL, true, kCGRenderingIntentDefault);
- UIImage *image = [UIImage imageWithCGImage:cgImage];
- CGImageRelease(cgImage);
- CGDataProviderRelease(provider);
- CGColorSpaceRelease(rgbColorSpace);
-
- CVPixelBufferUnlockBaseAddress(imageBuffer, 0);
- return image;
- }
CMSampleBuffer转UIImage
- + (UIImage *)imageFromSampleBuffer:(CMSampleBufferRef)sampleBufferRef {
- CVImageBufferRef pxbuffer = CMSampleBufferGetImageBuffer(sampleBufferRef);
- CIImage *ciImage = [CIImage imageWithCVImageBuffer:pxbuffer];
- CIContext *ciContext = [[CIContext alloc] init];
- CGImage *cgImage = [ciContext createCGImage:ciImage fromRect:ciImage.extent];
- UIImage *image = [UIImage imageWithCGImage:cgImage];
- return image;
- }