Last active
October 12, 2022 03:02
-
-
Save levantAJ/4e3e40ba2fa190fd88e329ede8f27f3f to your computer and use it in GitHub Desktop.
Create CMSampleBuffer from UIImage
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 ImageIO | |
import AVFoundation | |
var cvPixelBuffer: CVPixelBuffer? { | |
var pixelBuffer: CVPixelBuffer? = nil | |
let options: [NSObject: Any] = [ | |
kCVPixelBufferCGImageCompatibilityKey: false, | |
kCVPixelBufferCGBitmapContextCompatibilityKey: false, | |
] | |
let status = CVPixelBufferCreate(kCFAllocatorDefault, Int(size.width), Int(size.height), kCVPixelFormatType_32BGRA, options as CFDictionary, &pixelBuffer) | |
CVPixelBufferLockBaseAddress(pixelBuffer!, CVPixelBufferLockFlags(rawValue: 0)) | |
let pixelData = CVPixelBufferGetBaseAddress(pixelBuffer!) | |
let rgbColorSpace = CGColorSpaceCreateDeviceRGB() | |
let context = CGContext(data: pixelData, width: Int(size.width), height: Int(size.height), bitsPerComponent: 8, bytesPerRow: CVPixelBufferGetBytesPerRow(pixelBuffer!), space: rgbColorSpace, bitmapInfo: CGBitmapInfo.byteOrder32Little.rawValue) | |
context?.draw(cgImage!, in: CGRect(origin: .zero, size: size)) | |
CVPixelBufferUnlockBaseAddress(pixelBuffer!, CVPixelBufferLockFlags(rawValue: 0)) | |
return pixelBuffer | |
} | |
var cmSampleBuffer: CMSampleBuffer { | |
let pixelBuffer = cvPixelBuffer | |
var newSampleBuffer: CMSampleBuffer? = nil | |
var timimgInfo: CMSampleTimingInfo = kCMTimingInfoInvalid | |
var videoInfo: CMVideoFormatDescription? = nil | |
CMVideoFormatDescriptionCreateForImageBuffer(nil, pixelBuffer!, &videoInfo) | |
CMSampleBufferCreateForImageBuffer(kCFAllocatorDefault, pixelBuffer!, true, nil, nil, videoInfo!, &timimgInfo, &newSampleBuffer) | |
return newSampleBuffer! | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I got this error using your code, and I used CGImage instead of UIImage