Created
August 31, 2016 08:46
-
-
Save darcwader/094baa3add44c6b8cf65a9e4e9d46f78 to your computer and use it in GitHub Desktop.
Resize Image using vImage
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
extension UIImage { | |
func resizeVI(size:CGSize) -> UIImage? { | |
let cgImage = self.CGImage! | |
var format = vImage_CGImageFormat(bitsPerComponent: 8, bitsPerPixel: 32, colorSpace: nil, | |
bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.First.rawValue), | |
version: 0, decode: nil, renderingIntent: CGColorRenderingIntent.RenderingIntentDefault) | |
var sourceBuffer = vImage_Buffer() | |
defer { | |
sourceBuffer.data.dealloc(Int(sourceBuffer.height) * Int(sourceBuffer.height) * 4) | |
} | |
var error = vImageBuffer_InitWithCGImage(&sourceBuffer, &format, nil, cgImage, numericCast(kvImageNoFlags)) | |
guard error == kvImageNoError else { return nil } | |
// create a destination buffer | |
let scale = self.scale | |
let destWidth = Int(size.width) | |
let destHeight = Int(size.height) | |
let bytesPerPixel = CGImageGetBitsPerPixel(self.CGImage) / 8 | |
let destBytesPerRow = destWidth * bytesPerPixel | |
let destData = UnsafeMutablePointer<UInt8>.alloc(destHeight * destBytesPerRow) | |
defer { | |
destData.dealloc(destHeight * destBytesPerRow) | |
} | |
var destBuffer = vImage_Buffer(data: destData, height: vImagePixelCount(destHeight), width: vImagePixelCount(destWidth), rowBytes: destBytesPerRow) | |
// scale the image | |
error = vImageScale_ARGB8888(&sourceBuffer, &destBuffer, nil, numericCast(kvImageHighQualityResampling)) | |
guard error == kvImageNoError else { return nil } | |
// create a CGImage from vImage_Buffer | |
let destCGImage = vImageCreateCGImageFromBuffer(&destBuffer, &format, nil, nil, numericCast(kvImageNoFlags), &error)?.takeRetainedValue() | |
guard error == kvImageNoError else { return nil } | |
// create a UIImage | |
let resizedImage = destCGImage.flatMap { UIImage(CGImage: $0, scale: 0.0, orientation: self.imageOrientation) } | |
return resizedImage | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Latest version for Swift 5 -> https://gist.github.com/haikieu/45e045a0a582249fc492e858ab57a301