ImageProcessor.swift 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  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. /// Processor for resizing images. Only CG-based images are supported in macOS.
  149. public struct ResizingImageProcessor: ImageProcessor {
  150. public enum ContentMode {
  151. case none
  152. case aspectFit
  153. case aspectFill
  154. }
  155. public let identifier: String
  156. /// Target size of output image should be.
  157. public let targetSize: CGSize
  158. /// Target content mode of output image should be.
  159. /// Default to ContentMode.none
  160. public let targetContentMode: ContentMode
  161. /// Initialize a `ResizingImageProcessor`
  162. ///
  163. /// - parameter targetSize: Target size of output image should be.
  164. /// - parameter contentMode: Target content mode of output image should be.
  165. ///
  166. /// - returns: An initialized `ResizingImageProcessor`.
  167. public init(targetSize: CGSize, contentMode: ContentMode = .none) {
  168. self.targetSize = targetSize
  169. self.targetContentMode = contentMode
  170. if contentMode == .none {
  171. self.identifier = "com.onevcat.Kingfisher.ResizingImageProcessor(\(targetSize))"
  172. } else {
  173. self.identifier = "com.onevcat.Kingfisher.ResizingImageProcessor(\(targetSize), \(contentMode))"
  174. }
  175. }
  176. public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
  177. switch item {
  178. case .image(let image):
  179. var size: CGSize
  180. switch targetContentMode {
  181. case .none:
  182. size = targetSize
  183. case .aspectFill:
  184. size = image.size.kf.filling(targetSize)
  185. case .aspectFit:
  186. size = image.size.kf.constrained(targetSize)
  187. }
  188. return image.kf.resize(to: size)
  189. case .data(_):
  190. return (DefaultImageProcessor.default >> self).process(item: item, options: options)
  191. }
  192. }
  193. }
  194. /// Processor for adding blur effect to images. `Accelerate.framework` is used underhood for
  195. /// a better performance. A simulated Gaussian blur with specified blur radius will be applied.
  196. public struct BlurImageProcessor: ImageProcessor {
  197. public let identifier: String
  198. /// Blur radius for the simulated Gaussian blur.
  199. public let blurRadius: CGFloat
  200. /// Initialize a `BlurImageProcessor`
  201. ///
  202. /// - parameter blurRadius: Blur radius for the simulated Gaussian blur.
  203. ///
  204. /// - returns: An initialized `BlurImageProcessor`.
  205. public init(blurRadius: CGFloat) {
  206. self.blurRadius = blurRadius
  207. self.identifier = "com.onevcat.Kingfisher.BlurImageProcessor(\(blurRadius))"
  208. }
  209. public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
  210. switch item {
  211. case .image(let image):
  212. let radius = blurRadius * options.scaleFactor
  213. return image.kf.blurred(withRadius: radius)
  214. case .data(_):
  215. return (DefaultImageProcessor.default >> self).process(item: item, options: options)
  216. }
  217. }
  218. }
  219. /// Processor for adding an overlay to images. Only CG-based images are supported in macOS.
  220. public struct OverlayImageProcessor: ImageProcessor {
  221. public var identifier: String
  222. /// Overlay color will be used to overlay the input image.
  223. public let overlay: Color
  224. /// Fraction will be used when overlay the color to image.
  225. public let fraction: CGFloat
  226. /// Initialize an `OverlayImageProcessor`
  227. ///
  228. /// - parameter overlay: Overlay color will be used to overlay the input image.
  229. /// - parameter fraction: Fraction will be used when overlay the color to image.
  230. /// From 0.0 to 1.0. 0.0 means solid color, 1.0 means transparent overlay.
  231. ///
  232. /// - returns: An initialized `OverlayImageProcessor`.
  233. public init(overlay: Color, fraction: CGFloat = 0.5) {
  234. self.overlay = overlay
  235. self.fraction = fraction
  236. self.identifier = "com.onevcat.Kingfisher.OverlayImageProcessor(\(overlay.hex)_\(fraction))"
  237. }
  238. public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
  239. switch item {
  240. case .image(let image):
  241. return image.kf.overlaying(with: overlay, fraction: fraction)
  242. case .data(_):
  243. return (DefaultImageProcessor.default >> self).process(item: item, options: options)
  244. }
  245. }
  246. }
  247. /// Processor for tint images with color. Only CG-based images are supported.
  248. public struct TintImageProcessor: ImageProcessor {
  249. public let identifier: String
  250. /// Tint color will be used to tint the input image.
  251. public let tint: Color
  252. /// Initialize a `TintImageProcessor`
  253. ///
  254. /// - parameter tint: Tint color will be used to tint the input image.
  255. ///
  256. /// - returns: An initialized `TintImageProcessor`.
  257. public init(tint: Color) {
  258. self.tint = tint
  259. self.identifier = "com.onevcat.Kingfisher.TintImageProcessor(\(tint.hex))"
  260. }
  261. public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
  262. switch item {
  263. case .image(let image):
  264. return image.kf.tinted(with: tint)
  265. case .data(_):
  266. return (DefaultImageProcessor.default >> self).process(item: item, options: options)
  267. }
  268. }
  269. }
  270. /// Processor for applying some color control to images. Only CG-based images are supported.
  271. /// watchOS is not supported.
  272. public struct ColorControlsProcessor: ImageProcessor {
  273. public let identifier: String
  274. /// Brightness changing to image.
  275. public let brightness: CGFloat
  276. /// Contrast changing to image.
  277. public let contrast: CGFloat
  278. /// Saturation changing to image.
  279. public let saturation: CGFloat
  280. /// InputEV changing to image.
  281. public let inputEV: CGFloat
  282. /// Initialize a `ColorControlsProcessor`
  283. ///
  284. /// - parameter brightness: Brightness changing to image.
  285. /// - parameter contrast: Contrast changing to image.
  286. /// - parameter saturation: Saturation changing to image.
  287. /// - parameter inputEV: InputEV changing to image.
  288. ///
  289. /// - returns: An initialized `ColorControlsProcessor`
  290. public init(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) {
  291. self.brightness = brightness
  292. self.contrast = contrast
  293. self.saturation = saturation
  294. self.inputEV = inputEV
  295. self.identifier = "com.onevcat.Kingfisher.ColorControlsProcessor(\(brightness)_\(contrast)_\(saturation)_\(inputEV))"
  296. }
  297. public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
  298. switch item {
  299. case .image(let image):
  300. return image.kf.adjusted(brightness: brightness, contrast: contrast, saturation: saturation, inputEV: inputEV)
  301. case .data(_):
  302. return (DefaultImageProcessor.default >> self).process(item: item, options: options)
  303. }
  304. }
  305. }
  306. /// Processor for applying black and white effect to images. Only CG-based images are supported.
  307. /// watchOS is not supported.
  308. public struct BlackWhiteProcessor: ImageProcessor {
  309. public let identifier = "com.onevcat.Kingfisher.BlackWhiteProcessor"
  310. /// Initialize a `BlackWhiteProcessor`
  311. ///
  312. /// - returns: An initialized `BlackWhiteProcessor`
  313. public init() {}
  314. public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
  315. return ColorControlsProcessor(brightness: 0.0, contrast: 1.0, saturation: 0.0, inputEV: 0.7)
  316. .process(item: item, options: options)
  317. }
  318. }
  319. /// Concatenate two `ImageProcessor`s. `ImageProcessor.appen(another:)` is used internally.
  320. ///
  321. /// - parameter left: First processor.
  322. /// - parameter right: Second processor.
  323. ///
  324. /// - returns: The concatenated processor.
  325. public func >>(left: ImageProcessor, right: ImageProcessor) -> ImageProcessor {
  326. return left.append(another: right)
  327. }
  328. fileprivate extension Color {
  329. var hex: String {
  330. var r: CGFloat = 0
  331. var g: CGFloat = 0
  332. var b: CGFloat = 0
  333. var a: CGFloat = 0
  334. getRed(&r, green: &g, blue: &b, alpha: &a)
  335. let rInt = Int(r * 255) << 24
  336. let gInt = Int(g * 255) << 16
  337. let bInt = Int(b * 255) << 8
  338. let aInt = Int(a * 255)
  339. let rgba = rInt | gInt | bInt | aInt
  340. return String(format:"#%08x", rgba)
  341. }
  342. }