-
-
Save karosLi/14ad44fe8a1abaa61094697a65daf659 to your computer and use it in GitHub Desktop.
UIImage from CMSampleBuffer
This file contains hidden or 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
#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; | |
} |
This file contains hidden or 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
#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