ImageProcessor.swift 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  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` 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. /// Identifier of the processor.
  96. /// - Note: See documentation of `ImageProcessor` protocol for more.
  97. public let identifier = ""
  98. /// Initialize a `DefaultImageProcessor`
  99. public init() {}
  100. /// Process an input `ImageProcessItem` item to an image for this processor.
  101. ///
  102. /// - parameter item: Input item which will be processed by `self`
  103. /// - parameter options: Options when processing the item.
  104. ///
  105. /// - returns: The processed image.
  106. ///
  107. /// - Note: See documentation of `ImageProcessor` protocol for more.
  108. public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
  109. switch item {
  110. case .image(let image):
  111. return image
  112. case .data(let data):
  113. return Kingfisher<Image>.image(
  114. data: data,
  115. scale: options.scaleFactor,
  116. preloadAllGIFData: options.preloadAllGIFData,
  117. onlyFirstFrame: options.onlyLoadFirstFrame)
  118. }
  119. }
  120. }
  121. /// Processor for making round corner images. Only CG-based images are supported in macOS,
  122. /// if a non-CG image passed in, the processor will do nothing.
  123. public struct RoundCornerImageProcessor: ImageProcessor {
  124. /// Identifier of the processor.
  125. /// - Note: See documentation of `ImageProcessor` protocol for more.
  126. public let identifier: String
  127. /// Corner radius will be applied in processing.
  128. public let cornerRadius: CGFloat
  129. /// Target size of output image should be. If `nil`, the image will keep its original size after processing.
  130. public let targetSize: CGSize?
  131. /// Initialize a `RoundCornerImageProcessor`
  132. ///
  133. /// - parameter cornerRadius: Corner radius will be applied in processing.
  134. /// - parameter targetSize: Target size of output image should be. If `nil`,
  135. /// the image will keep its original size after processing.
  136. /// Default is `nil`.
  137. public init(cornerRadius: CGFloat, targetSize: CGSize? = nil) {
  138. self.cornerRadius = cornerRadius
  139. self.targetSize = targetSize
  140. if let size = targetSize {
  141. self.identifier = "com.onevcat.Kingfisher.RoundCornerImageProcessor(\(cornerRadius)_\(size))"
  142. } else {
  143. self.identifier = "com.onevcat.Kingfisher.RoundCornerImageProcessor(\(cornerRadius))"
  144. }
  145. }
  146. /// Process an input `ImageProcessItem` item to an image for this processor.
  147. ///
  148. /// - parameter item: Input item which will be processed by `self`
  149. /// - parameter options: Options when processing the item.
  150. ///
  151. /// - returns: The processed image.
  152. ///
  153. /// - Note: See documentation of `ImageProcessor` protocol for more.
  154. public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
  155. switch item {
  156. case .image(let image):
  157. let size = targetSize ?? image.kf.size
  158. return image.kf.image(withRoundRadius: cornerRadius, fit: size)
  159. case .data(_):
  160. return (DefaultImageProcessor.default >> self).process(item: item, options: options)
  161. }
  162. }
  163. }
  164. /// Specify how a size adjusts itself to fit a target size.
  165. ///
  166. /// - none: Not scale the content.
  167. /// - aspectFit: Scale the content to fit the size of the view by maintaining the aspect ratio.
  168. /// - aspectFill: Scale the content to fill the size of the view
  169. public enum ContentMode {
  170. case none
  171. case aspectFit
  172. case aspectFill
  173. }
  174. /// Processor for resizing images. Only CG-based images are supported in macOS.
  175. public struct ResizingImageProcessor: ImageProcessor {
  176. /// Identifier of the processor.
  177. /// - Note: See documentation of `ImageProcessor` protocol for more.
  178. public let identifier: String
  179. /// The reference size for resizing operation.
  180. public let referenceSize: CGSize
  181. /// Target content mode of output image should be.
  182. /// Default to ContentMode.none
  183. public let targetContentMode: ContentMode
  184. /// Initialize a `ResizingImageProcessor`.
  185. ///
  186. /// - Parameters:
  187. /// - referenceSize: The reference size for resizing operation.
  188. /// - mode: Target content mode of output image should be.
  189. ///
  190. /// - Note:
  191. /// The instance of `ResizingImageProcessor` will follow its `mode` property
  192. /// and try to resizing the input images to fit or fill the `referenceSize`.
  193. /// That means if you are using a `mode` besides of `.none`, you may get an
  194. /// image with its size not be the same as the `referenceSize`.
  195. ///
  196. /// **Example**: With input image size: {100, 200},
  197. /// `referenceSize`: {100, 100}, `mode`: `.aspectFit`,
  198. /// you will get an output image with size of {50, 100}, which "fit"s
  199. /// the `referenceSize`.
  200. ///
  201. /// If you need an output image exactly to be a specified size, append or use
  202. /// a `CroppingImageProcessor`.
  203. public init(referenceSize: CGSize, mode: ContentMode = .none) {
  204. self.referenceSize = referenceSize
  205. self.targetContentMode = mode
  206. if mode == .none {
  207. self.identifier = "com.onevcat.Kingfisher.ResizingImageProcessor(\(referenceSize))"
  208. } else {
  209. self.identifier = "com.onevcat.Kingfisher.ResizingImageProcessor(\(referenceSize), \(mode))"
  210. }
  211. }
  212. /// Process an input `ImageProcessItem` item to an image for this processor.
  213. ///
  214. /// - parameter item: Input item which will be processed by `self`
  215. /// - parameter options: Options when processing the item.
  216. ///
  217. /// - returns: The processed image.
  218. ///
  219. /// - Note: See documentation of `ImageProcessor` protocol for more.
  220. public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
  221. switch item {
  222. case .image(let image):
  223. return image.kf.resize(to: referenceSize, for: targetContentMode)
  224. case .data(_):
  225. return (DefaultImageProcessor.default >> self).process(item: item, options: options)
  226. }
  227. }
  228. }
  229. /// Processor for adding blur effect to images. `Accelerate.framework` is used underhood for
  230. /// a better performance. A simulated Gaussian blur with specified blur radius will be applied.
  231. public struct BlurImageProcessor: ImageProcessor {
  232. /// Identifier of the processor.
  233. /// - Note: See documentation of `ImageProcessor` protocol for more.
  234. public let identifier: String
  235. /// Blur radius for the simulated Gaussian blur.
  236. public let blurRadius: CGFloat
  237. /// Initialize a `BlurImageProcessor`
  238. ///
  239. /// - parameter blurRadius: Blur radius for the simulated Gaussian blur.
  240. public init(blurRadius: CGFloat) {
  241. self.blurRadius = blurRadius
  242. self.identifier = "com.onevcat.Kingfisher.BlurImageProcessor(\(blurRadius))"
  243. }
  244. /// Process an input `ImageProcessItem` item to an image for this processor.
  245. ///
  246. /// - parameter item: Input item which will be processed by `self`
  247. /// - parameter options: Options when processing the item.
  248. ///
  249. /// - returns: The processed image.
  250. ///
  251. /// - Note: See documentation of `ImageProcessor` protocol for more.
  252. public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
  253. switch item {
  254. case .image(let image):
  255. let radius = blurRadius * options.scaleFactor
  256. return image.kf.blurred(withRadius: radius)
  257. case .data(_):
  258. return (DefaultImageProcessor.default >> self).process(item: item, options: options)
  259. }
  260. }
  261. }
  262. /// Processor for adding an overlay to images. Only CG-based images are supported in macOS.
  263. public struct OverlayImageProcessor: ImageProcessor {
  264. /// Identifier of the processor.
  265. /// - Note: See documentation of `ImageProcessor` protocol for more.
  266. public let identifier: String
  267. /// Overlay color will be used to overlay the input image.
  268. public let overlay: Color
  269. /// Fraction will be used when overlay the color to image.
  270. public let fraction: CGFloat
  271. /// Initialize an `OverlayImageProcessor`
  272. ///
  273. /// - parameter overlay: Overlay color will be used to overlay the input image.
  274. /// - parameter fraction: Fraction will be used when overlay the color to image.
  275. /// From 0.0 to 1.0. 0.0 means solid color, 1.0 means transparent overlay.
  276. public init(overlay: Color, fraction: CGFloat = 0.5) {
  277. self.overlay = overlay
  278. self.fraction = fraction
  279. self.identifier = "com.onevcat.Kingfisher.OverlayImageProcessor(\(overlay.hex)_\(fraction))"
  280. }
  281. /// Process an input `ImageProcessItem` item to an image for this processor.
  282. ///
  283. /// - parameter item: Input item which will be processed by `self`
  284. /// - parameter options: Options when processing the item.
  285. ///
  286. /// - returns: The processed image.
  287. ///
  288. /// - Note: See documentation of `ImageProcessor` protocol for more.
  289. public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
  290. switch item {
  291. case .image(let image):
  292. return image.kf.overlaying(with: overlay, fraction: fraction)
  293. case .data(_):
  294. return (DefaultImageProcessor.default >> self).process(item: item, options: options)
  295. }
  296. }
  297. }
  298. /// Processor for tint images with color. Only CG-based images are supported.
  299. public struct TintImageProcessor: ImageProcessor {
  300. /// Identifier of the processor.
  301. /// - Note: See documentation of `ImageProcessor` protocol for more.
  302. public let identifier: String
  303. /// Tint color will be used to tint the input image.
  304. public let tint: Color
  305. /// Initialize a `TintImageProcessor`
  306. ///
  307. /// - parameter tint: Tint color will be used to tint the input image.
  308. public init(tint: Color) {
  309. self.tint = tint
  310. self.identifier = "com.onevcat.Kingfisher.TintImageProcessor(\(tint.hex))"
  311. }
  312. /// Process an input `ImageProcessItem` item to an image for this processor.
  313. ///
  314. /// - parameter item: Input item which will be processed by `self`
  315. /// - parameter options: Options when processing the item.
  316. ///
  317. /// - returns: The processed image.
  318. ///
  319. /// - Note: See documentation of `ImageProcessor` protocol for more.
  320. public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
  321. switch item {
  322. case .image(let image):
  323. return image.kf.tinted(with: tint)
  324. case .data(_):
  325. return (DefaultImageProcessor.default >> self).process(item: item, options: options)
  326. }
  327. }
  328. }
  329. /// Processor for applying some color control to images. Only CG-based images are supported.
  330. /// watchOS is not supported.
  331. public struct ColorControlsProcessor: ImageProcessor {
  332. /// Identifier of the processor.
  333. /// - Note: See documentation of `ImageProcessor` protocol for more.
  334. public let identifier: String
  335. /// Brightness changing to image.
  336. public let brightness: CGFloat
  337. /// Contrast changing to image.
  338. public let contrast: CGFloat
  339. /// Saturation changing to image.
  340. public let saturation: CGFloat
  341. /// InputEV changing to image.
  342. public let inputEV: CGFloat
  343. /// Initialize a `ColorControlsProcessor`
  344. ///
  345. /// - parameter brightness: Brightness changing to image.
  346. /// - parameter contrast: Contrast changing to image.
  347. /// - parameter saturation: Saturation changing to image.
  348. /// - parameter inputEV: InputEV changing to image.
  349. public init(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) {
  350. self.brightness = brightness
  351. self.contrast = contrast
  352. self.saturation = saturation
  353. self.inputEV = inputEV
  354. self.identifier = "com.onevcat.Kingfisher.ColorControlsProcessor(\(brightness)_\(contrast)_\(saturation)_\(inputEV))"
  355. }
  356. /// Process an input `ImageProcessItem` item to an image for this processor.
  357. ///
  358. /// - parameter item: Input item which will be processed by `self`
  359. /// - parameter options: Options when processing the item.
  360. ///
  361. /// - returns: The processed image.
  362. ///
  363. /// - Note: See documentation of `ImageProcessor` protocol for more.
  364. public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
  365. switch item {
  366. case .image(let image):
  367. return image.kf.adjusted(brightness: brightness, contrast: contrast, saturation: saturation, inputEV: inputEV)
  368. case .data(_):
  369. return (DefaultImageProcessor.default >> self).process(item: item, options: options)
  370. }
  371. }
  372. }
  373. /// Processor for applying black and white effect to images. Only CG-based images are supported.
  374. /// watchOS is not supported.
  375. public struct BlackWhiteProcessor: ImageProcessor {
  376. /// Identifier of the processor.
  377. /// - Note: See documentation of `ImageProcessor` protocol for more.
  378. public let identifier = "com.onevcat.Kingfisher.BlackWhiteProcessor"
  379. /// Initialize a `BlackWhiteProcessor`
  380. public init() {}
  381. /// Process an input `ImageProcessItem` item to an image for this processor.
  382. ///
  383. /// - parameter item: Input item which will be processed by `self`
  384. /// - parameter options: Options when processing the item.
  385. ///
  386. /// - returns: The processed image.
  387. ///
  388. /// - Note: See documentation of `ImageProcessor` protocol for more.
  389. public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
  390. return ColorControlsProcessor(brightness: 0.0, contrast: 1.0, saturation: 0.0, inputEV: 0.7)
  391. .process(item: item, options: options)
  392. }
  393. }
  394. /// Processor for cropping an image. Only CG-based images are supported.
  395. /// watchOS is not supported.
  396. public struct CroppingImageProcessor: ImageProcessor {
  397. /// Identifier of the processor.
  398. /// - Note: See documentation of `ImageProcessor` protocol for more.
  399. public let identifier: String
  400. /// Target size of output image should be.
  401. public let size: CGSize
  402. /// Anchor point from which the output size should be calculate.
  403. /// The anchor point is consisted by two values between 0.0 and 1.0.
  404. /// It indicates a related point in current image.
  405. /// See `CroppingImageProcessor.init(size:anchor:)` for more.
  406. public let anchor: CGPoint
  407. /// Initialize a `CroppingImageProcessor`
  408. ///
  409. /// - Parameters:
  410. /// - size: Target size of output image should be.
  411. /// - anchor: The anchor point from which the size should be calculated.
  412. /// Default is `CGPoint(x: 0.5, y: 0.5)`, which means the center of input image.
  413. /// - Note:
  414. /// The anchor point is consisted by two values between 0.0 and 1.0.
  415. /// It indicates a related point in current image, eg: (0.0, 0.0) for top-left
  416. /// corner, (0.5, 0.5) for center and (1.0, 1.0) for bottom-right corner.
  417. /// The `size` property of `CroppingImageProcessor` will be used along with
  418. /// `anchor` to calculate a target rectange in the size of image.
  419. ///
  420. /// The target size will be automatically calculated with a reasonable behavior.
  421. /// For example, when you have an image size of `CGSize(width: 100, height: 100)`,
  422. /// and a target size of `CGSize(width: 20, height: 20)`:
  423. /// - with a (0.0, 0.0) anchor (top-left), the crop rect will be `{0, 0, 20, 20}`;
  424. /// - with a (0.5, 0.5) anchor (center), it will be `{40, 40, 20, 20}`
  425. /// - while with a (1.0, 1.0) anchor (bottom-right), it will be `{80, 80, 20, 20}`
  426. public init(size: CGSize, anchor: CGPoint = CGPoint(x: 0.5, y: 0.5)) {
  427. self.size = size
  428. self.anchor = anchor
  429. self.identifier = "com.onevcat.Kingfisher.CroppingImageProcessor(\(size)_\(anchor))"
  430. }
  431. /// Process an input `ImageProcessItem` item to an image for this processor.
  432. ///
  433. /// - parameter item: Input item which will be processed by `self`
  434. /// - parameter options: Options when processing the item.
  435. ///
  436. /// - returns: The processed image.
  437. ///
  438. /// - Note: See documentation of `ImageProcessor` protocol for more.
  439. public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
  440. switch item {
  441. case .image(let image):
  442. return image.kf.crop(to: size, anchorOn: anchor)
  443. case .data(_): return (DefaultImageProcessor.default >> self).process(item: item, options: options)
  444. }
  445. }
  446. }
  447. /// Concatenate two `ImageProcessor`s. `ImageProcessor.appen(another:)` is used internally.
  448. ///
  449. /// - parameter left: First processor.
  450. /// - parameter right: Second processor.
  451. ///
  452. /// - returns: The concatenated processor.
  453. public func >>(left: ImageProcessor, right: ImageProcessor) -> ImageProcessor {
  454. return left.append(another: right)
  455. }
  456. fileprivate extension Color {
  457. var hex: String {
  458. var r: CGFloat = 0
  459. var g: CGFloat = 0
  460. var b: CGFloat = 0
  461. var a: CGFloat = 0
  462. getRed(&r, green: &g, blue: &b, alpha: &a)
  463. let rInt = Int(r * 255) << 24
  464. let gInt = Int(g * 255) << 16
  465. let bInt = Int(b * 255) << 8
  466. let aInt = Int(a * 255)
  467. let rgba = rInt | gInt | bInt | aInt
  468. return String(format:"#%08x", rgba)
  469. }
  470. }
  471. // MARK: - Deprecated
  472. extension ResizingImageProcessor {
  473. /// Reference size of output image should follow.
  474. @available(*, deprecated,
  475. message: "targetSize are renamed. Use `referenceSize` instead",
  476. renamed: "referenceSize")
  477. public var targetSize: CGSize {
  478. return referenceSize
  479. }
  480. /// Initialize a `ResizingImageProcessor`
  481. ///
  482. /// - parameter targetSize: Reference size of output image should follow.
  483. /// - parameter contentMode: Target content mode of output image should be.
  484. @available(*, deprecated,
  485. message: "targetSize and contentMode are renamed. Use `init(referenceSize:mode:)` instead",
  486. renamed: "init(referenceSize:mode:)")
  487. public init(targetSize: CGSize, contentMode: ContentMode = .none) {
  488. self.init(referenceSize: targetSize, mode: contentMode)
  489. }
  490. }