Filter.swift 5.4 KB

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