Filter.swift 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  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. #if os(macOS)
  28. import AppKit
  29. #else
  30. import UIKit
  31. #endif
  32. import CoreImage
  33. // Reuses the same CI Context for all CI drawings.
  34. struct SendableBox<T>: @unchecked Sendable {
  35. let value: T
  36. }
  37. private let ciContext = SendableBox(value: CIContext(options: nil))
  38. /// Represents the type of transformer method, which will be used to provide a ``Filter``.
  39. public typealias Transformer = (CIImage) -> CIImage?
  40. /// Represents an ``ImageProcessor`` based on a ``Filter``, for images of `CIImage`.
  41. ///
  42. /// You can use any ``Filter``, or in other words, a ``Transformer`` to convert a `CIImage` to another, to create a
  43. /// ``ImageProcessor`` type easily.
  44. public protocol CIImageProcessor: ImageProcessor {
  45. var filter: Filter { get }
  46. }
  47. extension CIImageProcessor {
  48. public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? {
  49. switch item {
  50. case .image(let image):
  51. return image.kf.apply(filter)
  52. case .data:
  53. return (DefaultImageProcessor.default |> self).process(item: item, options: options)
  54. }
  55. }
  56. }
  57. /// A wrapper struct for a `Transformer` of CIImage filters.
  58. ///
  59. /// A ``Filter`` value can be used to create an ``ImageProcessor`` for `CIImage`s.
  60. public struct Filter {
  61. let transform: Transformer
  62. /// Creates a ``Filter`` from a given ``Transformer``.
  63. ///
  64. /// - Parameter transform: The value defines how a `CIImage` can be converted to another one.
  65. public init(transform: @escaping Transformer) {
  66. self.transform = transform
  67. }
  68. /// Tint filter that applies a tint color to images.
  69. public static let tint: @Sendable (KFCrossPlatformColor) -> Filter = {
  70. color in
  71. Filter {
  72. input in
  73. let colorFilter = CIFilter(name: "CIConstantColorGenerator")!
  74. colorFilter.setValue(CIColor(color: color), forKey: kCIInputColorKey)
  75. let filter = CIFilter(name: "CISourceOverCompositing")!
  76. let colorImage = colorFilter.outputImage
  77. filter.setValue(colorImage, forKey: kCIInputImageKey)
  78. filter.setValue(input, forKey: kCIInputBackgroundImageKey)
  79. return filter.outputImage?.cropped(to: input.extent)
  80. }
  81. }
  82. /// Represents color control elements.
  83. ///
  84. /// It contains necessary variables which can be applied as a filter to `CIImage.applyingFilter` feature as
  85. /// "CIColorControls".
  86. public struct ColorElement {
  87. public let brightness: CGFloat
  88. public let contrast: CGFloat
  89. public let saturation: CGFloat
  90. public let inputEV: CGFloat
  91. /// Creates a ``ColorElement`` value with given parameters.
  92. /// - Parameters:
  93. /// - brightness: The brightness change applied to the image.
  94. /// - contrast: The contrast change applied to the image.
  95. /// - saturation: The saturation change applied to the image.
  96. /// - inputEV: The EV (F-stops brighter or darker) change applied to the image.
  97. public init(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) {
  98. self.brightness = brightness
  99. self.contrast = contrast
  100. self.saturation = saturation
  101. self.inputEV = inputEV
  102. }
  103. }
  104. /// Color control filter that applies color control changes to images.
  105. public static let colorControl: @Sendable (ColorElement) -> Filter = { arg -> Filter in
  106. return Filter { input in
  107. let paramsColor = [kCIInputBrightnessKey: arg.brightness,
  108. kCIInputContrastKey: arg.contrast,
  109. kCIInputSaturationKey: arg.saturation]
  110. let blackAndWhite = input.applyingFilter("CIColorControls", parameters: paramsColor)
  111. let paramsExposure = [kCIInputEVKey: arg.inputEV]
  112. return blackAndWhite.applyingFilter("CIExposureAdjust", parameters: paramsExposure)
  113. }
  114. }
  115. }
  116. extension KingfisherWrapper where Base: KFCrossPlatformImage {
  117. /// Applies a `Filter` containing a `CIImage` transformer to `self`.
  118. ///
  119. /// - Parameters:
  120. /// - filter: The filter used to transform `self`.
  121. /// - Returns: A transformed image by the input `Filter`.
  122. ///
  123. /// > Important: Only CG-based images are supported. If an error occurs during transformation,
  124. /// ``KingfisherWrapper/base`` will be returned.
  125. public func apply(_ filter: Filter) -> KFCrossPlatformImage {
  126. guard let cgImage = cgImage else {
  127. assertionFailure("[Kingfisher] Tint image only works for CG-based image.")
  128. return base
  129. }
  130. let inputImage = CIImage(cgImage: cgImage)
  131. guard let outputImage = filter.transform(inputImage) else {
  132. return base
  133. }
  134. guard let result = ciContext.value.createCGImage(outputImage, from: outputImage.extent) else {
  135. assertionFailure("[Kingfisher] Can not make an tint image within context.")
  136. return base
  137. }
  138. #if os(macOS)
  139. return fixedForRetinaPixel(cgImage: result, to: size)
  140. #else
  141. return KFCrossPlatformImage(cgImage: result, scale: base.scale, orientation: base.imageOrientation)
  142. #endif
  143. }
  144. }
  145. #endif