Skip to content

Instantly share code, notes, and snippets.

@jeffrafter
Created February 9, 2017 00:34
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeffrafter/ad8516d4ed7221a5cfd4b66d2f7f4ca1 to your computer and use it in GitHub Desktop.
Save jeffrafter/ad8516d4ed7221a5cfd4b66d2f7f4ca1 to your computer and use it in GitHub Desktop.
Resizing CGImage in Swift 3
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()
}
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)
@georgbachmann
Copy link

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

@cprovatas
Copy link

Same issue here

@amarincas
Copy link

Why are you passing alphaInfo as bitmapInfo?

@tempdeltavalue
Copy link

    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