Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iosdevie/b1dffdc9513039babc97684b9b432a4c to your computer and use it in GitHub Desktop.
Save iosdevie/b1dffdc9513039babc97684b9b432a4c to your computer and use it in GitHub Desktop.
extension UIImage{
func resize(newSize: CGSize) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
self.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
func toCVPixelBuffer() -> CVPixelBuffer? {
var pixelBuffer: CVPixelBuffer? = nil
let attr = [kCVPixelBufferCGImageCompatibilityKey: kCFBooleanTrue,
kCVPixelBufferCGBitmapContextCompatibilityKey: kCFBooleanTrue] as CFDictionary
let width = Int(self.size.width)
let height = Int(self.size.height)
CVPixelBufferCreate(kCFAllocatorDefault, width, height, kCVPixelFormatType_OneComponent8, attr, &pixelBuffer)
CVPixelBufferLockBaseAddress(pixelBuffer!, CVPixelBufferLockFlags(rawValue:0))
let colorspace = CGColorSpaceCreateDeviceGray()
let bitmapContext = CGContext(data: CVPixelBufferGetBaseAddress(pixelBuffer!), width: width, height: height, bitsPerComponent: 8, bytesPerRow: CVPixelBufferGetBytesPerRow(pixelBuffer!), space: colorspace, bitmapInfo: 0)!
guard let cg = self.cgImage else {
return nil
}
bitmapContext.draw(cg, in: CGRect(x: 0, y: 0, width: width, height: height))
return pixelBuffer
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment