Skip to content

Instantly share code, notes, and snippets.

@zadr
Created March 8, 2017 19:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zadr/0594f6649e39974730b69e3deb186e1c to your computer and use it in GitHub Desktop.
Save zadr/0594f6649e39974730b69e3deb186e1c to your computer and use it in GitHub Desktop.
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