Skip to content

Instantly share code, notes, and snippets.

@caojianhua
Last active June 10, 2017 20:48
Show Gist options
  • Save caojianhua/d189c2c3f8971c95c2f3 to your computer and use it in GitHub Desktop.
Save caojianhua/d189c2c3f8971c95c2f3 to your computer and use it in GitHub Desktop.
Create CVPixelBufferRef from an UIImage
+ (CVPixelBufferRef)pixelBufferFromImage:(UIImage *)image {
NSData * rawImageData = [UIImage RawRepresentation:image pixelFormat:SVPixelFormat_BGRA];
NSDictionary * attributes = @{
(NSString *)kCVPixelBufferIOSurfacePropertiesKey : @{},
(NSString *)kCVPixelBufferCGImageCompatibilityKey : @(YES),
(NSString *)kCVPixelBufferOpenGLESCompatibilityKey : @(YES),
(NSString *)kCVPixelBufferCGBitmapContextCompatibilityKey : @(YES),
};
CVPixelBufferRef pixelBufferRef = NULL;
CVReturn status = CVPixelBufferCreateWithBytes(kCFAllocatorDefault, image.size.width * image.scale, image.size.height * image.scale, kCVPixelFormatType_32BGRA, (void *)rawImageData.bytes, (NSUInteger)image.size.width * image.scale * 4, NULL, NULL, (__bridge CFDictionaryRef)(attributes), &pixelBufferRef);
if (kCVReturnSuccess != status) {
CrazyInnerLoge(@"create pixel buffer from UIImage failed!");
return NULL;
}
return pixelBufferRef;
}
@Pranoy1c
Copy link

Where did you get the [UIImage RawRepresentation:image pixelFormat:SVPixelFormat_BGRA] method? it says doesn't exist.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment