Filter.swift 6.4 KB

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