ImageProcessor.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. //
  2. // ImageProcessor.swift
  3. // Kingfisher
  4. //
  5. // Created by Wei Wang on 2016/08/26.
  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 Foundation
  27. import CoreGraphics
  28. /// The item which could be processed by an `ImageProcessor`
  29. ///
  30. /// - image: Input image
  31. /// - data: Input data
  32. public enum ImageProcessItem {
  33. case image(Image)
  34. case data(Data)
  35. }
  36. /// An `ImageProcessor` could be used to convert some downloaded data to an image.
  37. public protocol ImageProcessor {
  38. /// Identifier of the processor. It will be used to identify the processor when
  39. /// caching and retriving an image. You might want to make sure that processors with
  40. /// same properties/functionality have the same identifiers.
  41. var identifier: String { get }
  42. /// Process an input `ImageProcessItem` item to an image for this processor.
  43. ///
  44. /// - parameter item: Input item which will be processed by `self`
  45. /// - parameter options: Options when processing the item.
  46. ///
  47. /// - returns: The processed image.
  48. ///
  49. /// - Note: The return value will be `nil` if processing failed while converting data to image.
  50. /// If input item is already an image and there is any errors in processing, the input
  51. /// image itself will be returned.
  52. /// - Note: Most processor only supports CG-based images.
  53. /// watchOS is not supported for processers containing filter, the input image will be returned directly on watchOS.
  54. func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image?
  55. }
  56. typealias ProcessorImp = ((ImageProcessItem, KingfisherOptionsInfo) -> Image?)
  57. public extension ImageProcessor {
  58. /// Append an `ImageProcessor` to another. The identifier of the new `ImageProcessor`
  59. /// will be "\(self.identifier)|>\(another.identifier)>".
  60. ///
  61. /// - parameter another: An `ImageProcessor` you want to append to `self`.
  62. ///
  63. /// - returns: The new `ImageProcessor`. It will process the image in the order
  64. /// of the two processors concatenated.
  65. public func append(another: ImageProcessor) -> ImageProcessor {
  66. let newIdentifier = identifier.appending("|>\(another.identifier)")
  67. return GeneralProcessor(identifier: newIdentifier) {
  68. item, options in
  69. if let image = self.process(item: item, options: options) {
  70. return another.process(item: .image(image), options: options)
  71. } else {
  72. return nil
  73. }
  74. }
  75. }
  76. }
  77. fileprivate struct GeneralProcessor: ImageProcessor {
  78. let identifier: String
  79. let p: ProcessorImp
  80. func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
  81. return p(item, options)
  82. }
  83. }
  84. /// The default processor. It convert the input data to a valid image.
  85. /// Images of .PNG, .JPEG and .GIF format are supported.
  86. /// If an image is given, `DefaultImageProcessor` will do nothing on it and just return that image.
  87. public struct DefaultImageProcessor: ImageProcessor {
  88. /// A default `DefaultImageProcessor` could be used across.
  89. public static let `default` = DefaultImageProcessor()
  90. public let identifier = ""
  91. /// Initialize a `DefaultImageProcessor`
  92. ///
  93. /// - returns: An initialized `DefaultImageProcessor`.
  94. public init() {}
  95. public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
  96. switch item {
  97. case .image(let image):
  98. return image
  99. case .data(let data):
  100. return Image.kf_image(data: data, scale: options.scaleFactor, preloadAllGIFData: options.preloadAllGIFData)
  101. }
  102. }
  103. }
  104. /// Processor for making round corner images. Only CG-based images are supported in macOS,
  105. /// if a non-CG image passed in, the processor will do nothing.
  106. public struct RoundCornerImageProcessor: ImageProcessor {
  107. public let identifier: String
  108. /// Corner radius will be applied in processing.
  109. public let cornerRadius: CGFloat
  110. /// Target size of output image should be. If `nil`, the image will keep its original size after processing.
  111. public let targetSize: CGSize?
  112. /// Initialize a `RoundCornerImageProcessor`
  113. ///
  114. /// - parameter cornerRadius: Corner radius will be applied in processing.
  115. /// - parameter targetSize: Target size of output image should be. If `nil`,
  116. /// the image will keep its original size after processing.
  117. /// Default is `nil`.
  118. ///
  119. /// - returns: An initialized `RoundCornerImageProcessor`.
  120. public init(cornerRadius: CGFloat, targetSize: CGSize? = nil) {
  121. self.cornerRadius = cornerRadius
  122. self.targetSize = targetSize
  123. if let size = targetSize {
  124. self.identifier = "com.onevcat.Kingfisher.RoundCornerImageProcessor(\(cornerRadius)_\(size))"
  125. } else {
  126. self.identifier = "com.onevcat.Kingfisher.RoundCornerImageProcessor(\(cornerRadius))"
  127. }
  128. }
  129. public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
  130. switch item {
  131. case .image(let image):
  132. let size = targetSize ?? image.kf_size
  133. return image.kf_image(withRoundRadius: cornerRadius, fit: size, scale: options.scaleFactor)
  134. case .data(_):
  135. return (DefaultImageProcessor() |> self).process(item: item, options: options)
  136. }
  137. }
  138. }
  139. /// Processor for resizing images. Only CG-based images are supported in macOS.
  140. public struct ResizingImageProcessor: ImageProcessor {
  141. public let identifier: String
  142. /// Target size of output image should be.
  143. public let targetSize: CGSize
  144. /// Initialize a `ResizingImageProcessor`
  145. ///
  146. /// - parameter targetSize: Target size of output image should be.
  147. ///
  148. /// - returns: An initialized `ResizingImageProcessor`.
  149. public init(targetSize: CGSize) {
  150. self.targetSize = targetSize
  151. self.identifier = "com.onevcat.Kingfisher.ResizingImageProcessor(\(targetSize))"
  152. }
  153. public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
  154. switch item {
  155. case .image(let image):
  156. return image.kf_resize(to: targetSize)
  157. case .data(_):
  158. return (DefaultImageProcessor() |> self).process(item: item, options: options)
  159. }
  160. }
  161. }
  162. /// Processor for adding blur effect to images. `Accelerate.framework` is used underhood for
  163. /// a better performance. A simulated Gaussian blur with specified blur radius will be applied.
  164. public struct BlurImageProcessor: ImageProcessor {
  165. public let identifier: String
  166. /// Blur radius for the simulated Gaussian blur.
  167. public let blurRadius: CGFloat
  168. /// Initialize a `BlurImageProcessor`
  169. ///
  170. /// - parameter blurRadius: Blur radius for the simulated Gaussian blur.
  171. ///
  172. /// - returns: An initialized `BlurImageProcessor`.
  173. public init(blurRadius: CGFloat) {
  174. self.blurRadius = blurRadius
  175. self.identifier = "com.onevcat.Kingfisher.BlurImageProcessor(\(blurRadius))"
  176. }
  177. public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
  178. switch item {
  179. case .image(let image):
  180. let radius = blurRadius * options.scaleFactor
  181. return image.kf_blurred(withRadius: radius)
  182. case .data(_):
  183. return (DefaultImageProcessor() |> self).process(item: item, options: options)
  184. }
  185. }
  186. }
  187. /// Processor for adding an overlay to images. Only CG-based images are supported in macOS.
  188. public struct OverlayImageProcessor: ImageProcessor {
  189. public var identifier: String
  190. /// Overlay color will be used to overlay the input image.
  191. public let overlay: Color
  192. /// Fraction will be used when overlay the color to image.
  193. public let fraction: CGFloat
  194. /// Initialize an `OverlayImageProcessor`
  195. ///
  196. /// - parameter overlay: Overlay color will be used to overlay the input image.
  197. /// - parameter fraction: Fraction will be used when overlay the color to image.
  198. /// From 0.0 to 1.0. 0.0 means solid color, 1.0 means transparent overlay.
  199. ///
  200. /// - returns: An initialized `OverlayImageProcessor`.
  201. public init(overlay: Color, fraction: CGFloat = 0.5) {
  202. self.overlay = overlay
  203. self.fraction = fraction
  204. self.identifier = "com.onevcat.Kingfisher.OverlayImageProcessor(\(overlay.hex)_\(fraction))"
  205. }
  206. public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
  207. switch item {
  208. case .image(let image):
  209. return image.kf_overlaying(with: overlay, fraction: fraction)
  210. case .data(_):
  211. return (DefaultImageProcessor() |> self).process(item: item, options: options)
  212. }
  213. }
  214. }
  215. /// Processor for tint images with color. Only CG-based images are supported.
  216. public struct TintImageProcessor: ImageProcessor {
  217. public let identifier: String
  218. /// Tint color will be used to tint the input image.
  219. public let tint: Color
  220. /// Initialize a `TintImageProcessor`
  221. ///
  222. /// - parameter tint: Tint color will be used to tint the input image.
  223. ///
  224. /// - returns: An initialized `TintImageProcessor`.
  225. public init(tint: Color) {
  226. self.tint = tint
  227. self.identifier = "com.onevcat.Kingfisher.TintImageProcessor(\(tint.hex))"
  228. }
  229. public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
  230. switch item {
  231. case .image(let image):
  232. return image.kf_tinted(with: tint)
  233. case .data(_):
  234. return (DefaultImageProcessor() |> self).process(item: item, options: options)
  235. }
  236. }
  237. }
  238. /// Processor for applying some color control to images. Only CG-based images are supported.
  239. /// watchOS is not supported.
  240. public struct ColorControlsProcessor: ImageProcessor {
  241. public let identifier: String
  242. /// Brightness changing to image.
  243. public let brightness: CGFloat
  244. /// Contrast changing to image.
  245. public let contrast: CGFloat
  246. /// Saturation changing to image.
  247. public let saturation: CGFloat
  248. /// InputEV changing to image.
  249. public let inputEV: CGFloat
  250. /// Initialize a `ColorControlsProcessor`
  251. ///
  252. /// - parameter brightness: Brightness changing to image.
  253. /// - parameter contrast: Contrast changing to image.
  254. /// - parameter saturation: Saturation changing to image.
  255. /// - parameter inputEV: InputEV changing to image.
  256. ///
  257. /// - returns: An initialized `ColorControlsProcessor`
  258. public init(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) {
  259. self.brightness = brightness
  260. self.contrast = contrast
  261. self.saturation = saturation
  262. self.inputEV = inputEV
  263. self.identifier = "com.onevcat.Kingfisher.ColorControlsProcessor(\(brightness)_\(contrast)_\(saturation)_\(inputEV))"
  264. }
  265. public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
  266. switch item {
  267. case .image(let image):
  268. return image.kf_adjusted(brightness: brightness, contrast: contrast, saturation: saturation, inputEV: inputEV)
  269. case .data(_):
  270. return (DefaultImageProcessor() |> self).process(item: item, options: options)
  271. }
  272. }
  273. }
  274. /// Processor for applying black and white effect to images. Only CG-based images are supported.
  275. /// watchOS is not supported.
  276. public struct BlackWhiteProcessor: ImageProcessor {
  277. public let identifier = "com.onevcat.Kingfisher.BlackWhiteProcessor"
  278. /// Initialize a `BlackWhiteProcessor`
  279. ///
  280. /// - returns: An initialized `BlackWhiteProcessor`
  281. public init() {}
  282. public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
  283. return ColorControlsProcessor(brightness: 0.0, contrast: 1.0, saturation: 0.0, inputEV: 0.7)
  284. .process(item: item, options: options)
  285. }
  286. }
  287. infix operator |>: AdditionPrecedence
  288. /// Concatenate two `ImageProcessor`s. `ImageProcessor.appen(another:)` is used internally.
  289. ///
  290. /// - parameter left: First processor.
  291. /// - parameter right: Second processor.
  292. ///
  293. /// - returns: The concatenated processor.
  294. public func |>(left: ImageProcessor, right: ImageProcessor) -> ImageProcessor {
  295. return left.append(another: right)
  296. }
  297. fileprivate extension Color {
  298. var hex: String {
  299. var r: CGFloat = 0
  300. var g: CGFloat = 0
  301. var b: CGFloat = 0
  302. var a: CGFloat = 0
  303. getRed(&r, green: &g, blue: &b, alpha: &a)
  304. let rgba = Int(r * 255) << 24 | Int(g * 255) << 16 | Int(b * 255) << 8 | Int(a * 255)
  305. return String(format:"#%08x", rgba)
  306. }
  307. }