Filter.swift 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. //
  2. // Filter.swift
  3. // Kingfisher
  4. //
  5. // Created by Wei Wang on 2016/08/31.
  6. //
  7. // Copyright (c) 2019 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. // Reuse the same CI Context for all CI drawing.
  28. private let ciContext = CIContext(options: nil)
  29. /// Represents the type of transformer method, which will be used in to provide a `Filter`.
  30. public typealias Transformer = (CIImage) -> CIImage?
  31. /// Represents a processor based on a `CIImage` `Filter`.
  32. /// It requires a filter to create an `ImageProcessor`.
  33. public protocol CIImageProcessor: ImageProcessor {
  34. var filter: Filter { get }
  35. }
  36. extension CIImageProcessor {
  37. /// Processes the input `ImageProcessItem` with this processor.
  38. ///
  39. /// - Parameters:
  40. /// - item: Input item which will be processed by `self`.
  41. /// - options: Options when processing the item.
  42. /// - Returns: The processed image.
  43. ///
  44. /// - Note: See documentation of `ImageProcessor` protocol for more.
  45. public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> Image? {
  46. switch item {
  47. case .image(let image):
  48. return image.kf.apply(filter)
  49. case .data:
  50. return (DefaultImageProcessor.default >> self).process(item: item, options: options)
  51. }
  52. }
  53. }
  54. /// A wrapper struct for a `Transformer` of CIImage filters. A `Filter`
  55. /// value could be used to create a `CIImage` processor.
  56. public struct Filter {
  57. let transform: Transformer
  58. public init(transform: @escaping Transformer) {
  59. self.transform = transform
  60. }
  61. /// Tint filter which will apply a tint color to images.
  62. public static var tint: (Color) -> Filter = {
  63. color in
  64. Filter {
  65. input in
  66. let colorFilter = CIFilter(name: "CIConstantColorGenerator")!
  67. colorFilter.setValue(CIColor(color: color), forKey: kCIInputColorKey)
  68. let filter = CIFilter(name: "CISourceOverCompositing")!
  69. let colorImage = colorFilter.outputImage
  70. filter.setValue(colorImage, forKey: kCIInputImageKey)
  71. filter.setValue(input, forKey: kCIInputBackgroundImageKey)
  72. return filter.outputImage?.cropped(to: input.extent)
  73. }
  74. }
  75. /// Represents color control elements. It is a tuple of
  76. /// `(brightness, contrast, saturation, inputEV)`
  77. public typealias ColorElement = (CGFloat, CGFloat, CGFloat, CGFloat)
  78. /// Color control filter which will apply color control change to images.
  79. public static var colorControl: (ColorElement) -> Filter = { arg -> Filter in
  80. let (brightness, contrast, saturation, inputEV) = arg
  81. return Filter { input in
  82. let paramsColor = [kCIInputBrightnessKey: brightness,
  83. kCIInputContrastKey: contrast,
  84. kCIInputSaturationKey: saturation]
  85. let blackAndWhite = input.applyingFilter("CIColorControls", parameters: paramsColor)
  86. let paramsExposure = [kCIInputEVKey: inputEV]
  87. return blackAndWhite.applyingFilter("CIExposureAdjust", parameters: paramsExposure)
  88. }
  89. }
  90. }
  91. extension KingfisherWrapper where Base: Image {
  92. /// Applies a `Filter` containing `CIImage` transformer to `self`.
  93. ///
  94. /// - Parameter filter: The filter used to transform `self`.
  95. /// - Returns: A transformed image by input `Filter`.
  96. ///
  97. /// - Note:
  98. /// Only CG-based images are supported. If any error happens
  99. /// during transforming, `self` will be returned.
  100. public func apply(_ filter: Filter) -> Image {
  101. guard let cgImage = cgImage else {
  102. assertionFailure("[Kingfisher] Tint image only works for CG-based image.")
  103. return base
  104. }
  105. let inputImage = CIImage(cgImage: cgImage)
  106. guard let outputImage = filter.transform(inputImage) else {
  107. return base
  108. }
  109. guard let result = ciContext.createCGImage(outputImage, from: outputImage.extent) else {
  110. assertionFailure("[Kingfisher] Can not make an tint image within context.")
  111. return base
  112. }
  113. #if os(macOS)
  114. return fixedForRetinaPixel(cgImage: result, to: size)
  115. #else
  116. return Image(cgImage: result, scale: base.scale, orientation: base.imageOrientation)
  117. #endif
  118. }
  119. }