ImageProcessor.swift 14 KB

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