Filter.swift 5.3 KB

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