Skip to content

Instantly share code, notes, and snippets.

@kean
Created August 22, 2016 14:57
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 kean/a720d17a0b5726b145bff08eb8fb406e to your computer and use it in GitHub Desktop.
Save kean/a720d17a0b5726b145bff08eb8fb406e to your computer and use it in GitHub Desktop.
CoreImageHelpers
// MARK - CoreImage
private let sharedContext = CIContext(options: [kCIContextPriorityRequestLow: true])
/// Core Image helper methods.
public extension UIImage {
/// Applies closure with a filter to the image.
///
// Performance considerations. Chaining multiple CIFilter objects is much
/// more efficient then using ProcessorComposition to combine multiple
/// instances of CoreImageFilter class. Avoid unnecessary texture transfers
/// between the CPU and GPU.
///
/// - parameter context: Core Image context, uses shared context by default.
/// - parameter filter: Closure for applying image filter.
public func applyFilter(context: CIContext = sharedContext, closure: (CIImage) -> CIImage?) -> UIImage? {
func inputImage(for image: UIImage) -> CIImage? {
if let image = image.cgImage {
return CIImage(cgImage: image)
}
if let image = image.ciImage {
return image
}
return nil
}
guard let inputImage = inputImage(for: self), let outputImage = closure(inputImage) else {
return nil
}
guard let imageRef = context.createCGImage(outputImage, from: inputImage.extent) else {
return nil
}
return UIImage(cgImage: imageRef, scale: scale, orientation: imageOrientation)
}
/// Applies filter to the image.
///
/// - parameter context: Core Image context, uses shared context by default.
/// - parameter filter: Image filter.
public func applyFilter(_ filter: CIFilter?, context: CIContext = sharedContext) -> UIImage? {
guard let filter = filter else {
return nil
}
return applyFilter(context: context) {
filter.setValue($0, forKey: kCIInputImageKey)
return filter.outputImage
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment