Skip to content

Instantly share code, notes, and snippets.

@shalyf
Last active January 6, 2024 20:46
Show Gist options
  • Save shalyf/98a7bd8c0e4c960730afa826e7ab25bc to your computer and use it in GitHub Desktop.
Save shalyf/98a7bd8c0e4c960730afa826e7ab25bc to your computer and use it in GitHub Desktop.
CVPixelBuffer通过vImage转换成CGImage
import Accelerate.vImage
func getImageBuffer(from pixelBuffer: CVPixelBuffer) -> vImage_Buffer? {
var buffer = vImage_Buffer()
let bitmapInfo = CGBitmapInfo(rawValue: CGBitmapInfo.byteOrder32Little.rawValue | CGImageAlphaInfo.first.rawValue)
var cgFormat = vImage_CGImageFormat(bitsPerComponent: 8,
bitsPerPixel: 32,
colorSpace: nil,
bitmapInfo: bitmapInfo,
version: 0,
decode: nil,
renderingIntent: .defaultIntent)
let cvFormat = vImageCVImageFormat_Create(kCVPixelFormatType_420YpCbCr8BiPlanarFullRange,
kvImage_ARGBToYpCbCrMatrix_ITU_R_709_2,
kCVImageBufferChromaLocation_TopLeft,
CGColorSpaceCreateDeviceRGB(), 0).takeRetainedValue()
var error: vImage_Error
error = vImageBuffer_InitWithCVPixelBuffer(&buffer,
&cgFormat,
pixelBuffer,
cvFormat,
nil,
vImage_Flags(0))
guard error == kvImageNoError else { return nil }
return buffer
}
func getPixelBuffer(from buffer: vImage_Buffer, width: Int, height: Int) -> CVPixelBuffer? {
var buffer = buffer
let bitmapInfo = CGBitmapInfo(rawValue: CGBitmapInfo.byteOrder32Little.rawValue | CGImageAlphaInfo.first.rawValue)
var cgFormat = vImage_CGImageFormat(bitsPerComponent: 8,
bitsPerPixel: 32,
colorSpace: nil,
bitmapInfo: bitmapInfo,
version: 0,
decode: nil,
renderingIntent: .defaultIntent)
let cvFormat = vImageCVImageFormat_Create(kCVPixelFormatType_420YpCbCr8BiPlanarFullRange,
kvImage_ARGBToYpCbCrMatrix_ITU_R_709_2,
kCVImageBufferChromaLocation_TopLeft,
CGColorSpaceCreateDeviceRGB(), 0).takeRetainedValue()
var pixelBuffer: CVPixelBuffer?
let status = CVPixelBufferCreate(kCFAllocatorDefault,
width,
height,
kCVPixelFormatType_420YpCbCr8BiPlanarFullRange,
nil,
&pixelBuffer)
guard status == kCVReturnSuccess else { return nil }
let error = vImageBuffer_CopyToCVPixelBuffer(&buffer,
&cgFormat,
pixelBuffer!,
cvFormat,
nil,
vImage_Flags(0))
guard error == kvImageNoError else { return nil }
return pixelBuffer
}
func getCGImage(from buffer: vImage_Buffer) -> CGImage? {
var buffer = buffer
let bitmapInfo = CGBitmapInfo(rawValue: CGBitmapInfo.byteOrder32Little.rawValue | CGImageAlphaInfo.first.rawValue)
var cgFormat = vImage_CGImageFormat(bitsPerComponent: 8, bitsPerPixel: 32, colorSpace: nil, bitmapInfo: bitmapInfo, version: 0, decode: nil, renderingIntent: .defaultIntent)
var error: vImage_Error = kvImageNoError
let cgImage = vImageCreateCGImageFromBuffer(&buffer, &cgFormat, nil, nil, vImage_Flags(0), &error).takeRetainedValue()
free(buffer.data)
guard error == kvImageNoError else { return nil }
return cgImage
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment