Skip to content

Instantly share code, notes, and snippets.

@zadr
Created Mar 8, 2017
Embed
What would you like to do?
UIImage from CMSampleBuffer
#import <CoreMedia/CoreMedia.h>
#import <CoreVideo/CoreVideo.h>
#import <UIKit/UIKit.h>
// https://developer.apple.com/library/content/qa/qa1702/_index.html
+ (UIImage * _Nullable)imageWithSampleBuffer:(CMSampleBufferRef _Nonnull)sampleBuffer {
UIImage *returnValue = nil;
CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
CVPixelBufferLockBaseAddress(imageBuffer, 0); {
void *baseAddress = CVPixelBufferGetBaseAddress(imageBuffer);
size_t bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer);
size_t width = CVPixelBufferGetWidth(imageBuffer);
size_t height = CVPixelBufferGetHeight(imageBuffer);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(baseAddress, width, height, 8, bytesPerRow, colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst);
CGImageRef quartzImage = CGBitmapContextCreateImage(context);
returnValue = [UIImage imageWithCGImage:quartzImage];
CGImageRelease(quartzImage);
CGContextRelease(context);
CGColorSpaceRelease(colorSpace);
} CVPixelBufferUnlockBaseAddress(imageBuffer, 0);
return returnValue;
}
#import <CoreMedia/CoreMedia.h>
#import <UIKit/UIKit.h>
#import <VideoToolbox/VideoToolbox.h>
+ (UIImage * _Nullable)imageWithSampleBuffer:(CMSampleBufferRef _Nonnull)sampleBuffer {
CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
CGImageRef image = NULL;
OSStatus createdImage = VTCreateCGImageFromCVPixelBuffer(imageBuffer, NULL, &image);
if (createdImage == noErr) {
return [UIImage imageWithCGImage:image];
}
return nil;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment