Created
October 23, 2019 18:38
Star
You must be signed in to star a gist
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 { | |
func resize(to newSize: CGSize) -> UIImage? { | |
guard self.size != newSize else { return self } | |
UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0) | |
self.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)) | |
defer { UIGraphicsEndImageContext() } | |
return UIGraphicsGetImageFromCurrentImageContext() | |
} | |
func pixelBuffer() -> CVPixelBuffer? { | |
let width = Int(self.size.width) | |
let height = Int(self.size.height) | |
let attrs = [kCVPixelBufferCGImageCompatibilityKey: kCFBooleanTrue, kCVPixelBufferCGBitmapContextCompatibilityKey: kCFBooleanTrue] as CFDictionary | |
var pixelBuffer: CVPixelBuffer? | |
let status = CVPixelBufferCreate(kCFAllocatorDefault, width, height, kCVPixelFormatType_32ARGB, attrs, &pixelBuffer) | |
guard status == kCVReturnSuccess else { | |
return nil | |
} | |
CVPixelBufferLockBaseAddress(pixelBuffer!, CVPixelBufferLockFlags(rawValue: 0)) | |
let pixelData = CVPixelBufferGetBaseAddress(pixelBuffer!) | |
let rgbColorSpace = CGColorSpaceCreateDeviceRGB() | |
guard let context = CGContext(data: pixelData, width: width, height: height, bitsPerComponent: 8, bytesPerRow: CVPixelBufferGetBytesPerRow(pixelBuffer!), space: rgbColorSpace, bitmapInfo: CGImageAlphaInfo.noneSkipFirst.rawValue) else { | |
return nil | |
} | |
context.translateBy(x: 0, y: CGFloat(height)) | |
context.scaleBy(x: 1.0, y: -1.0) | |
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