Created
February 19, 2019 10:14
-
-
Save kshala-ford/5f10b8be912439da6e1d05bd489e1924 to your computer and use it in GitHub Desktop.
Crop a sample buffer to a view and return a pixel buffer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
+ (CVPixelBufferRef)croppedPixelBufferFromSampleBuffer:(CMSampleBufferRef)buffer frame:(CGRect)frame { | |
if (buffer == nil) return nil; | |
CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(buffer); | |
if (imageBuffer == nil) return nil; | |
CIImage *ciImage = [CIImage imageWithCVPixelBuffer:imageBuffer]; | |
ciImage = [ciImage imageByCroppingToRect:frame]; | |
CFDictionaryRef empty; // empty value for attr IOSurface | |
empty = CFDictionaryCreate(kCFAllocatorDefault, NULL, NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); | |
CFMutableDictionaryRef attrs = CFDictionaryCreateMutable(kCFAllocatorDefault, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); | |
CFDictionarySetValue(attrs, kCVPixelBufferIOSurfacePropertiesKey, empty); | |
CVPixelBufferRef pixelBuffer; | |
CVPixelBufferCreate(kCFAllocatorSystemDefault, frame.size.width, frame.size.height, kCVPixelFormatType_32BGRA, attrs, &pixelBuffer); | |
CVPixelBufferLockBaseAddress(pixelBuffer, 0); | |
CIContext *ciContext = [CIContext contextWithOptions: nil]; | |
[ciContext render:ciImage toCVPixelBuffer:pixelBuffer]; | |
CVPixelBufferUnlockBaseAddress(pixelBuffer, 0); | |
CFRelease(attrs); | |
CFRelease(empty); | |
return pixelBuffer; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment