Created
February 9, 2017 00:34
-
-
Save jeffrafter/ad8516d4ed7221a5cfd4b66d2f7f4ca1 to your computer and use it in GitHub Desktop.
Resizing CGImage in Swift 3
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
func resize(_ image: CGImage) -> CGImage? { | |
var ratio: Float = 0.0 | |
let imageWidth = Float(image.width) | |
let imageHeight = Float(image.height) | |
let maxWidth: Float = 1024.0 | |
let maxHeight: Float = 768.0 | |
// Get ratio (landscape or portrait) | |
if (imageWidth > imageHeight) { | |
ratio = maxWidth / imageWidth | |
} else { | |
ratio = maxHeight / imageHeight | |
} | |
// Calculate new size based on the ratio | |
if ratio > 1 { | |
ratio = 1 | |
} | |
let width = imageWidth * ratio | |
let height = imageHeight * ratio | |
guard let colorSpace = image.colorSpace else { return nil } | |
guard let context = CGContext(data: nil, width: Int(width), height: Int(height), bitsPerComponent: image.bitsPerComponent, bytesPerRow: image.bytesPerRow, space: colorSpace, bitmapInfo: image.alphaInfo.rawValue) else { return nil } | |
// draw image to context (resizing it) | |
context.interpolationQuality = .high | |
context.draw(image, in: CGRect(x: 0, y: 0, width: Int(width), height: Int(height))) | |
// extract resulting image from context | |
return context.makeImage() | |
} |
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
let ciImage = CIImage(cgImage: image) | |
let filter = CIFilter(name: "CILanczosScaleTransform")! | |
filter.setValue(ciImage, forKey: "inputImage") | |
filter.setValue(ratio, forKey: "inputScale") | |
filter.setValue(1.0, forKey: "inputAspectRatio") | |
let outputImage = filter.value(forKey: "outputImage") as! CIImage | |
let context = CIContext(options: [kCIContextUseSoftwareRenderer: false]) | |
return context.createCGImage(outputImage, from: outputImage.extent) |
Same issue here
Why are you passing alphaInfo as bitmapInfo?
if ratio > 1 {
ratio = 1
}
what if ratio needed to be > 1?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just had a look at your resize function, but for me the CGContext (line 24) is always nil?!? Any ideas? I am running it on macOS