Filter.swift 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. //
  2. // Filter.swift
  3. // Kingfisher
  4. //
  5. // Created by Wei Wang on 2016/08/31.
  6. //
  7. // Copyright (c) 2018 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(transform: @escaping Transformer) {
  50. self.transform = transform
  51. }
  52. /// Tint filter which will apply a tint color to images.
  53. public static var tint: (Color) -> Filter = {
  54. color in
  55. Filter(transform: { 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?.cropped(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 = { arg -> Filter in
  68. let (brightness, contrast, saturation, inputEV) = arg
  69. return Filter(transform: { input in
  70. let paramsColor = [kCIInputBrightnessKey: brightness,
  71. kCIInputContrastKey: contrast,
  72. kCIInputSaturationKey: saturation]
  73. let paramsExposure = [kCIInputEVKey: inputEV]
  74. let blackAndWhite = input.applyingFilter("CIColorControls", parameters: paramsColor)
  75. return blackAndWhite.applyingFilter("CIExposureAdjust", parameters: paramsExposure)
  76. })
  77. }
  78. }
  79. // MARK: - Deprecated
  80. extension Filter {
  81. @available(*, deprecated, message: "Use init(transform:) instead.", renamed: "init(transform:)")
  82. public init(tranform: @escaping Transformer) {
  83. self.transform = tranform
  84. }
  85. }
  86. extension KingfisherClass where Base: Image {
  87. /// Apply a `Filter` containing `CIImage` transformer to `self`.
  88. ///
  89. /// - parameter filter: The filter used to transform `self`.
  90. ///
  91. /// - returns: A transformed image by input `Filter`.
  92. ///
  93. /// - Note: Only CG-based images are supported. If any error happens during transforming, `self` will be returned.
  94. public func apply(_ filter: Filter) -> Image {
  95. guard let cgImage = cgImage else {
  96. assertionFailure("[Kingfisher] Tint image only works for CG-based image.")
  97. return base
  98. }
  99. let inputImage = CIImage(cgImage: cgImage)
  100. guard let outputImage = filter.transform(inputImage) else {
  101. return base
  102. }
  103. guard let result = ciContext.createCGImage(outputImage, from: outputImage.extent) else {
  104. assertionFailure("[Kingfisher] Can not make an tint image within context.")
  105. return base
  106. }
  107. #if os(macOS)
  108. return fixedForRetinaPixel(cgImage: result, to: size)
  109. #else
  110. return Image(cgImage: result, scale: base.scale, orientation: base.imageOrientation)
  111. #endif
  112. }
  113. }