ImageProcessor.swift 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. //
  2. // ImageProcessor.swift
  3. // Kingfisher
  4. //
  5. // Created by Wei Wang on 2016/08/26.
  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 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(
  106. data: data,
  107. scale: options.scaleFactor,
  108. preloadAllGIFData: options.preloadAllGIFData,
  109. onlyFirstFrame: options.onlyLoadFirstFrame)
  110. }
  111. }
  112. }
  113. /// Processor for making round corner images. Only CG-based images are supported in macOS,
  114. /// if a non-CG image passed in, the processor will do nothing.
  115. public struct RoundCornerImageProcessor: ImageProcessor {
  116. public let identifier: String
  117. /// Corner radius will be applied in processing.
  118. public let cornerRadius: CGFloat
  119. /// Target size of output image should be. If `nil`, the image will keep its original size after processing.
  120. public let targetSize: CGSize?
  121. /// Initialize a `RoundCornerImageProcessor`
  122. ///
  123. /// - parameter cornerRadius: Corner radius will be applied in processing.
  124. /// - parameter targetSize: Target size of output image should be. If `nil`,
  125. /// the image will keep its original size after processing.
  126. /// Default is `nil`.
  127. ///
  128. /// - returns: An initialized `RoundCornerImageProcessor`.
  129. public init(cornerRadius: CGFloat, targetSize: CGSize? = nil) {
  130. self.cornerRadius = cornerRadius
  131. self.targetSize = targetSize
  132. if let size = targetSize {
  133. self.identifier = "com.onevcat.Kingfisher.RoundCornerImageProcessor(\(cornerRadius)_\(size))"
  134. } else {
  135. self.identifier = "com.onevcat.Kingfisher.RoundCornerImageProcessor(\(cornerRadius))"
  136. }
  137. }
  138. public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
  139. switch item {
  140. case .image(let image):
  141. let size = targetSize ?? image.kf.size
  142. return image.kf.image(withRoundRadius: cornerRadius, fit: size)
  143. case .data(_):
  144. return (DefaultImageProcessor.default >> self).process(item: item, options: options)
  145. }
  146. }
  147. }
  148. /// Specify how a size adjusts itself to fit a target.
  149. ///
  150. /// - none: Not scale the content.
  151. /// - aspectFit: Scale the content to fit the size of the view by maintaining the aspect ratio.
  152. /// - aspectFill: Scale the content to fill the size of the view
  153. public enum ContentMode {
  154. case none
  155. case aspectFit
  156. case aspectFill
  157. }
  158. /// Processor for resizing images. Only CG-based images are supported in macOS.
  159. public struct ResizingImageProcessor: ImageProcessor {
  160. public let identifier: String
  161. /// Target size of output image should be.
  162. public let targetSize: CGSize
  163. /// Target content mode of output image should be.
  164. /// Default to ContentMode.none
  165. public let targetContentMode: ContentMode
  166. /// Initialize a `ResizingImageProcessor`
  167. ///
  168. /// - parameter targetSize: Target size of output image should be.
  169. /// - parameter contentMode: Target content mode of output image should be.
  170. ///
  171. /// - returns: An initialized `ResizingImageProcessor`.
  172. public init(targetSize: CGSize, contentMode: ContentMode = .none) {
  173. self.targetSize = targetSize
  174. self.targetContentMode = contentMode
  175. if contentMode == .none {
  176. self.identifier = "com.onevcat.Kingfisher.ResizingImageProcessor(\(targetSize))"
  177. } else {
  178. self.identifier = "com.onevcat.Kingfisher.ResizingImageProcessor(\(targetSize), \(contentMode))"
  179. }
  180. }
  181. public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
  182. switch item {
  183. case .image(let image):
  184. return image.kf.resize(to: targetSize, for: targetContentMode)
  185. case .data(_):
  186. return (DefaultImageProcessor.default >> self).process(item: item, options: options)
  187. }
  188. }
  189. }
  190. /// Processor for adding blur effect to images. `Accelerate.framework` is used underhood for
  191. /// a better performance. A simulated Gaussian blur with specified blur radius will be applied.
  192. public struct BlurImageProcessor: ImageProcessor {
  193. public let identifier: String
  194. /// Blur radius for the simulated Gaussian blur.
  195. public let blurRadius: CGFloat
  196. /// Initialize a `BlurImageProcessor`
  197. ///
  198. /// - parameter blurRadius: Blur radius for the simulated Gaussian blur.
  199. ///
  200. /// - returns: An initialized `BlurImageProcessor`.
  201. public init(blurRadius: CGFloat) {
  202. self.blurRadius = blurRadius
  203. self.identifier = "com.onevcat.Kingfisher.BlurImageProcessor(\(blurRadius))"
  204. }
  205. public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
  206. switch item {
  207. case .image(let image):
  208. let radius = blurRadius * options.scaleFactor
  209. return image.kf.blurred(withRadius: radius)
  210. case .data(_):
  211. return (DefaultImageProcessor.default >> self).process(item: item, options: options)
  212. }
  213. }
  214. }
  215. /// Processor for adding an overlay to images. Only CG-based images are supported in macOS.
  216. public struct OverlayImageProcessor: ImageProcessor {
  217. public var identifier: String
  218. /// Overlay color will be used to overlay the input image.
  219. public let overlay: Color
  220. /// Fraction will be used when overlay the color to image.
  221. public let fraction: CGFloat
  222. /// Initialize an `OverlayImageProcessor`
  223. ///
  224. /// - parameter overlay: Overlay color will be used to overlay the input image.
  225. /// - parameter fraction: Fraction will be used when overlay the color to image.
  226. /// From 0.0 to 1.0. 0.0 means solid color, 1.0 means transparent overlay.
  227. ///
  228. /// - returns: An initialized `OverlayImageProcessor`.
  229. public init(overlay: Color, fraction: CGFloat = 0.5) {
  230. self.overlay = overlay
  231. self.fraction = fraction
  232. self.identifier = "com.onevcat.Kingfisher.OverlayImageProcessor(\(overlay.hex)_\(fraction))"
  233. }
  234. public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
  235. switch item {
  236. case .image(let image):
  237. return image.kf.overlaying(with: overlay, fraction: fraction)
  238. case .data(_):
  239. return (DefaultImageProcessor.default >> self).process(item: item, options: options)
  240. }
  241. }
  242. }
  243. /// Processor for tint images with color. Only CG-based images are supported.
  244. public struct TintImageProcessor: ImageProcessor {
  245. public let identifier: String
  246. /// Tint color will be used to tint the input image.
  247. public let tint: Color
  248. /// Initialize a `TintImageProcessor`
  249. ///
  250. /// - parameter tint: Tint color will be used to tint the input image.
  251. ///
  252. /// - returns: An initialized `TintImageProcessor`.
  253. public init(tint: Color) {
  254. self.tint = tint
  255. self.identifier = "com.onevcat.Kingfisher.TintImageProcessor(\(tint.hex))"
  256. }
  257. public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
  258. switch item {
  259. case .image(let image):
  260. return image.kf.tinted(with: tint)
  261. case .data(_):
  262. return (DefaultImageProcessor.default >> self).process(item: item, options: options)
  263. }
  264. }
  265. }
  266. /// Processor for applying some color control to images. Only CG-based images are supported.
  267. /// watchOS is not supported.
  268. public struct ColorControlsProcessor: ImageProcessor {
  269. public let identifier: String
  270. /// Brightness changing to image.
  271. public let brightness: CGFloat
  272. /// Contrast changing to image.
  273. public let contrast: CGFloat
  274. /// Saturation changing to image.
  275. public let saturation: CGFloat
  276. /// InputEV changing to image.
  277. public let inputEV: CGFloat
  278. /// Initialize a `ColorControlsProcessor`
  279. ///
  280. /// - parameter brightness: Brightness changing to image.
  281. /// - parameter contrast: Contrast changing to image.
  282. /// - parameter saturation: Saturation changing to image.
  283. /// - parameter inputEV: InputEV changing to image.
  284. ///
  285. /// - returns: An initialized `ColorControlsProcessor`
  286. public init(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) {
  287. self.brightness = brightness
  288. self.contrast = contrast
  289. self.saturation = saturation
  290. self.inputEV = inputEV
  291. self.identifier = "com.onevcat.Kingfisher.ColorControlsProcessor(\(brightness)_\(contrast)_\(saturation)_\(inputEV))"
  292. }
  293. public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
  294. switch item {
  295. case .image(let image):
  296. return image.kf.adjusted(brightness: brightness, contrast: contrast, saturation: saturation, inputEV: inputEV)
  297. case .data(_):
  298. return (DefaultImageProcessor.default >> self).process(item: item, options: options)
  299. }
  300. }
  301. }
  302. /// Processor for applying black and white effect to images. Only CG-based images are supported.
  303. /// watchOS is not supported.
  304. public struct BlackWhiteProcessor: ImageProcessor {
  305. public let identifier = "com.onevcat.Kingfisher.BlackWhiteProcessor"
  306. /// Initialize a `BlackWhiteProcessor`
  307. ///
  308. /// - returns: An initialized `BlackWhiteProcessor`
  309. public init() {}
  310. public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
  311. return ColorControlsProcessor(brightness: 0.0, contrast: 1.0, saturation: 0.0, inputEV: 0.7)
  312. .process(item: item, options: options)
  313. }
  314. }
  315. /// Concatenate two `ImageProcessor`s. `ImageProcessor.appen(another:)` is used internally.
  316. ///
  317. /// - parameter left: First processor.
  318. /// - parameter right: Second processor.
  319. ///
  320. /// - returns: The concatenated processor.
  321. public func >>(left: ImageProcessor, right: ImageProcessor) -> ImageProcessor {
  322. return left.append(another: right)
  323. }
  324. fileprivate extension Color {
  325. var hex: String {
  326. var r: CGFloat = 0
  327. var g: CGFloat = 0
  328. var b: CGFloat = 0
  329. var a: CGFloat = 0
  330. getRed(&r, green: &g, blue: &b, alpha: &a)
  331. let rInt = Int(r * 255) << 24
  332. let gInt = Int(g * 255) << 16
  333. let bInt = Int(b * 255) << 8
  334. let aInt = Int(a * 255)
  335. let rgba = rInt | gInt | bInt | aInt
  336. return String(format:"#%08x", rgba)
  337. }
  338. }