Filter.swift 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. //
  2. // Filter.swift
  3. // Kingfisher
  4. //
  5. // Created by Wei Wang on 2016/08/31.
  6. //
  7. // Copyright (c) 2016 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(let data):
  42. return Image.kf_image(data: data, scale: options.scaleFactor, preloadAllGIFData: options.preloadAllGIFData)
  43. }
  44. }
  45. }
  46. /// Wrapper for a `Transformer` of CIImage filters.
  47. public struct Filter {
  48. let transform: Transformer
  49. /// Tint filter which will apply a tint color to images.
  50. public static var tint: (Color) -> Filter = {
  51. color in
  52. Filter { input in
  53. let colorFilter = CIFilter(name: "CIConstantColorGenerator")!
  54. colorFilter.setValue(CIColor(color: color), forKey: kCIInputColorKey)
  55. let colorImage = colorFilter.outputImage
  56. let filter = CIFilter(name: "CISourceOverCompositing")!
  57. filter.setValue(colorImage, forKey: kCIInputImageKey)
  58. filter.setValue(input, forKey: kCIInputBackgroundImageKey)
  59. return filter.outputImage?.cropping(to: input.extent)
  60. }
  61. }
  62. public typealias ColorElement = (CGFloat, CGFloat, CGFloat, CGFloat)
  63. /// Color control filter which will apply color control change to images.
  64. public static var colorControl: (ColorElement) -> Filter = {
  65. brightness, contrast, saturation, inputEV in
  66. Filter { input in
  67. let paramsColor = [kCIInputBrightnessKey: brightness,
  68. kCIInputContrastKey: contrast,
  69. kCIInputSaturationKey: saturation]
  70. let blackAndWhite = input.applyingFilter("CIColorControls", withInputParameters: paramsColor)
  71. let paramsExposure = [kCIInputEVKey: inputEV]
  72. return blackAndWhite.applyingFilter("CIExposureAdjust", withInputParameters: paramsExposure)
  73. }
  74. }
  75. }
  76. public extension Image {
  77. /// Apply a `Filter` containing `CIImage` transformer to `self`.
  78. ///
  79. /// - parameter filter: The filter used to transform `self`.
  80. ///
  81. /// - returns: A transformed image by input `Filter`.
  82. ///
  83. /// - Note: Only CG-based images are supported. If any error happens during transforming, `self` will be returned.
  84. public func kf_apply(_ filter: Filter) -> Image {
  85. guard let cgImage = cgImage else {
  86. assertionFailure("[Kingfisher] Tint image only works for CG-based image.")
  87. return self
  88. }
  89. let inputImage = CIImage(cgImage: cgImage)
  90. guard let outputImage = filter.transform(inputImage) else {
  91. return self
  92. }
  93. guard let result = ciContext.createCGImage(outputImage, from: outputImage.extent) else {
  94. assertionFailure("[Kingfisher] Can not make an tint image within context.")
  95. return self
  96. }
  97. #if os(macOS)
  98. return kf_fixedForRetinaPixel(cgImage: result, to: kf_size)
  99. #else
  100. return Image(cgImage: result)
  101. #endif
  102. }
  103. }