Created
September 9, 2017 00:08
-
-
Save francoismarceau29/abac55c22f6e440800d1d73d72bf2225 to your computer and use it in GitHub Desktop.
UIImage to CVPixelBuffer
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 UIKit | |
extension UIImage { | |
func toCVPixelBuffer() -> CVPixelBuffer? { | |
let attrs = [kCVPixelBufferCGImageCompatibilityKey: kCFBooleanTrue, kCVPixelBufferCGBitmapContextCompatibilityKey: kCFBooleanTrue] as CFDictionary | |
var pixelBuffer : CVPixelBuffer? | |
let status = CVPixelBufferCreate(kCFAllocatorDefault, Int(self.size.width), Int(self.size.height), kCVPixelFormatType_32ARGB, attrs, &pixelBuffer) | |
guard status == kCVReturnSuccess else { | |
return nil | |
} | |
if let pixelBuffer = pixelBuffer { | |
CVPixelBufferLockBaseAddress(pixelBuffer, CVPixelBufferLockFlags(rawValue: 0)) | |
let pixelData = CVPixelBufferGetBaseAddress(pixelBuffer) | |
let rgbColorSpace = CGColorSpaceCreateDeviceRGB() | |
let context = CGContext(data: pixelData, width: Int(self.size.width), height: Int(self.size.height), bitsPerComponent: 8, bytesPerRow: CVPixelBufferGetBytesPerRow(pixelBuffer), space: rgbColorSpace, bitmapInfo: CGImageAlphaInfo.noneSkipFirst.rawValue) | |
context?.translateBy(x: 0, y: self.size.height) | |
context?.scaleBy(x: 1.0, y: -1.0) | |
UIGraphicsPushContext(context!) | |
self.draw(in: CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height)) | |
UIGraphicsPopContext() | |
CVPixelBufferUnlockBaseAddress(pixelBuffer, CVPixelBufferLockFlags(rawValue: 0)) | |
return pixelBuffer | |
} | |
return nil | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment