Created
January 18, 2019 08:49
-
-
Save stinger/4b544946fbcdad9c360ff577b8bb9219 to your computer and use it in GitHub Desktop.
This file contains 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 { | |
/** | |
Resizes the image to width x height and converts it to an RGB CVPixelBuffer. | |
*/ | |
public func pixelBuffer(width: Int, height: Int) -> CVPixelBuffer? { | |
var maybePixelBuffer: CVPixelBuffer? | |
let attrs = [kCVPixelBufferCGImageCompatibilityKey: kCFBooleanTrue, | |
kCVPixelBufferCGBitmapContextCompatibilityKey: kCFBooleanTrue] | |
let status = CVPixelBufferCreate(kCFAllocatorDefault, | |
width, | |
height, | |
kCVPixelFormatType_32ARGB, | |
attrs as CFDictionary, | |
&maybePixelBuffer) | |
guard status == kCVReturnSuccess, let pixelBuffer = maybePixelBuffer else { | |
return nil | |
} | |
CVPixelBufferLockBaseAddress(pixelBuffer, CVPixelBufferLockFlags(rawValue: 0)) | |
let pixelData = CVPixelBufferGetBaseAddress(pixelBuffer) | |
guard let context = CGContext(data: pixelData, | |
width: width, | |
height: height, | |
bitsPerComponent: 8, | |
bytesPerRow: CVPixelBufferGetBytesPerRow(pixelBuffer), | |
space: CGColorSpaceCreateDeviceRGB(), | |
bitmapInfo: CGImageAlphaInfo.noneSkipFirst.rawValue) | |
else { | |
return nil | |
} | |
context.translateBy(x: 0, y: CGFloat(height)) | |
context.scaleBy(x: 1, y: -1) | |
UIGraphicsPushContext(context) | |
self.draw(in: CGRect(x: 0, y: 0, width: width, height: height)) | |
UIGraphicsPopContext() | |
CVPixelBufferUnlockBaseAddress(pixelBuffer, CVPixelBufferLockFlags(rawValue: 0)) | |
return pixelBuffer | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment