Filter.swift 5.6 KB

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