Filter.swift 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. //
  2. // Filter.swift
  3. // Kingfisher
  4. //
  5. // Created by Wei Wang on 2016/08/31.
  6. //
  7. // Copyright (c) 2018 Wei Wang <onevcat@gmail.com>
  8. //
  9. // Permission is hereby granted, free of charge, to any person obtaining a copy
  10. // of this software and associated documentation files (the "Software"), to deal
  11. // in the Software without restriction, including without limitation the rights
  12. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. // copies of the Software, and to permit persons to whom the Software is
  14. // furnished to do so, subject to the following conditions:
  15. //
  16. // The above copyright notice and this permission notice shall be included in
  17. // all copies or substantial portions of the Software.
  18. //
  19. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. // THE SOFTWARE.
  26. import CoreImage
  27. import Accelerate
  28. // Reuse the same CI Context for all CI drawing.
  29. private let ciContext = CIContext(options: nil)
  30. /// Transformer method which will be used in to provide a `Filter`.
  31. public typealias Transformer = (CIImage) -> CIImage?
  32. /// Supply a filter to create an `ImageProcessor`.
  33. public protocol CIImageProcessor: ImageProcessor {
  34. var filter: Filter { get }
  35. }
  36. extension CIImageProcessor {
  37. public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
  38. switch item {
  39. case .image(let image):
  40. return image.kf.apply(filter)
  41. case .data(_):
  42. return (DefaultImageProcessor.default >> self).process(item: item, options: options)
  43. }
  44. }
  45. }
  46. /// Wrapper for a `Transformer` of CIImage filters.
  47. public struct Filter {
  48. let transform: Transformer
  49. public init(tranform: @escaping Transformer) {
  50. self.transform = tranform
  51. }
  52. /// Tint filter which will apply a tint color to images.
  53. public static var tint: (Color) -> Filter = {
  54. color in
  55. Filter { input in
  56. let colorFilter = CIFilter(name: "CIConstantColorGenerator")!
  57. colorFilter.setValue(CIColor(color: color), forKey: kCIInputColorKey)
  58. let colorImage = colorFilter.outputImage
  59. let filter = CIFilter(name: "CISourceOverCompositing")!
  60. filter.setValue(colorImage, forKey: kCIInputImageKey)
  61. filter.setValue(input, forKey: kCIInputBackgroundImageKey)
  62. #if swift(>=4.0)
  63. return filter.outputImage?.cropped(to: input.extent)
  64. #else
  65. return filter.outputImage?.cropping(to: input.extent)
  66. #endif
  67. }
  68. }
  69. public typealias ColorElement = (CGFloat, CGFloat, CGFloat, CGFloat)
  70. /// Color control filter which will apply color control change to images.
  71. public static var colorControl: (ColorElement) -> Filter = { arg -> Filter in
  72. let (brightness, contrast, saturation, inputEV) = arg
  73. return Filter { input in
  74. let paramsColor = [kCIInputBrightnessKey: brightness,
  75. kCIInputContrastKey: contrast,
  76. kCIInputSaturationKey: saturation]
  77. let paramsExposure = [kCIInputEVKey: inputEV]
  78. #if swift(>=4.0)
  79. let blackAndWhite = input.applyingFilter("CIColorControls", parameters: paramsColor)
  80. return blackAndWhite.applyingFilter("CIExposureAdjust", parameters: paramsExposure)
  81. #else
  82. let blackAndWhite = input.applyingFilter("CIColorControls", withInputParameters: paramsColor)
  83. return blackAndWhite.applyingFilter("CIExposureAdjust", withInputParameters: paramsExposure)
  84. #endif
  85. }
  86. }
  87. }
  88. extension Kingfisher where Base: Image {
  89. /// Apply a `Filter` containing `CIImage` transformer to `self`.
  90. ///
  91. /// - parameter filter: The filter used to transform `self`.
  92. ///
  93. /// - returns: A transformed image by input `Filter`.
  94. ///
  95. /// - Note: Only CG-based images are supported. If any error happens during transforming, `self` will be returned.
  96. public func apply(_ filter: Filter) -> Image {
  97. guard let cgImage = cgImage else {
  98. assertionFailure("[Kingfisher] Tint image only works for CG-based image.")
  99. return base
  100. }
  101. let inputImage = CIImage(cgImage: cgImage)
  102. guard let outputImage = filter.transform(inputImage) else {
  103. return base
  104. }
  105. guard let result = ciContext.createCGImage(outputImage, from: outputImage.extent) else {
  106. assertionFailure("[Kingfisher] Can not make an tint image within context.")
  107. return base
  108. }
  109. #if os(macOS)
  110. return fixedForRetinaPixel(cgImage: result, to: size)
  111. #else
  112. return Image(cgImage: result, scale: base.scale, orientation: base.imageOrientation)
  113. #endif
  114. }
  115. }