ImageProcessor.swift 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709
  1. //
  2. // ImageProcessor.swift
  3. // Kingfisher
  4. //
  5. // Created by Wei Wang on 2016/08/26.
  6. //
  7. // Copyright (c) 2018 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. #if os(macOS)
  29. import AppKit
  30. #endif
  31. /// The item which could be processed by an `ImageProcessor`
  32. ///
  33. /// - image: Input image
  34. /// - data: Input data
  35. public enum ImageProcessItem {
  36. case image(Image)
  37. case data(Data)
  38. }
  39. /// An `ImageProcessor` would be used to convert some downloaded data to an image.
  40. public protocol ImageProcessor {
  41. /// Identifier of the processor. It will be used to identify the processor when
  42. /// caching and retrieving an image. You might want to make sure that processors with
  43. /// same properties/functionality have the same identifiers, so correct processed images
  44. /// could be retrieved with proper key.
  45. ///
  46. /// - Note: Do not supply an empty string for a customized processor, which is already taken by
  47. /// the `DefaultImageProcessor`. It is recommended to use a reverse domain name notation
  48. /// string of your own for the identifier.
  49. var identifier: String { get }
  50. /// Process an input `ImageProcessItem` item to an image for this processor.
  51. ///
  52. /// - parameter item: Input item which will be processed by `self`
  53. /// - parameter options: Options when processing the item.
  54. ///
  55. /// - returns: The processed image.
  56. ///
  57. /// - Note: The return value will be `nil` if processing failed while converting data to image.
  58. /// If input item is already an image and there is any errors in processing, the input
  59. /// image itself will be returned.
  60. /// - Note: Most processor only supports CG-based images.
  61. /// watchOS is not supported for processors containing filter, the input image will be returned directly on watchOS.
  62. func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image?
  63. }
  64. typealias ProcessorImp = ((ImageProcessItem, KingfisherOptionsInfo) -> Image?)
  65. public extension ImageProcessor {
  66. /// Append an `ImageProcessor` to another. The identifier of the new `ImageProcessor`
  67. /// will be "\(self.identifier)|>\(another.identifier)".
  68. ///
  69. /// - parameter another: An `ImageProcessor` you want to append to `self`.
  70. ///
  71. /// - returns: The new `ImageProcessor` will process the image in the order
  72. /// of the two processors concatenated.
  73. public func append(another: ImageProcessor) -> ImageProcessor {
  74. let newIdentifier = identifier.appending("|>\(another.identifier)")
  75. return GeneralProcessor(identifier: newIdentifier) {
  76. item, options in
  77. if let image = self.process(item: item, options: options) {
  78. return another.process(item: .image(image), options: options)
  79. } else {
  80. return nil
  81. }
  82. }
  83. }
  84. }
  85. func ==(left: ImageProcessor, right: ImageProcessor) -> Bool {
  86. return left.identifier == right.identifier
  87. }
  88. func !=(left: ImageProcessor, right: ImageProcessor) -> Bool {
  89. return !(left == right)
  90. }
  91. fileprivate struct GeneralProcessor: ImageProcessor {
  92. let identifier: String
  93. let p: ProcessorImp
  94. func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
  95. return p(item, options)
  96. }
  97. }
  98. /// The default processor. It convert the input data to a valid image.
  99. /// Images of .PNG, .JPEG and .GIF format are supported.
  100. /// If an image is given, `DefaultImageProcessor` will do nothing on it and just return that image.
  101. public struct DefaultImageProcessor: ImageProcessor {
  102. /// A default `DefaultImageProcessor` could be used across.
  103. public static let `default` = DefaultImageProcessor()
  104. /// Identifier of the processor.
  105. /// - Note: See documentation of `ImageProcessor` protocol for more.
  106. public let identifier = ""
  107. /// Initialize a `DefaultImageProcessor`
  108. public init() {}
  109. /// Process an input `ImageProcessItem` item to an image for this processor.
  110. ///
  111. /// - parameter item: Input item which will be processed by `self`
  112. /// - parameter options: Options when processing the item.
  113. ///
  114. /// - returns: The processed image.
  115. ///
  116. /// - Note: See documentation of `ImageProcessor` protocol for more.
  117. public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
  118. switch item {
  119. case .image(let image):
  120. return image.kf.scaled(to: options.scaleFactor)
  121. case .data(let data):
  122. return KingfisherClass.image(data: data, options: options.imageCreatingOptions)
  123. }
  124. }
  125. }
  126. public struct RectCorner: OptionSet {
  127. public let rawValue: Int
  128. public static let topLeft = RectCorner(rawValue: 1 << 0)
  129. public static let topRight = RectCorner(rawValue: 1 << 1)
  130. public static let bottomLeft = RectCorner(rawValue: 1 << 2)
  131. public static let bottomRight = RectCorner(rawValue: 1 << 3)
  132. public static let all: RectCorner = [.topLeft, .topRight, .bottomLeft, .bottomRight]
  133. public init(rawValue: Int) {
  134. self.rawValue = rawValue
  135. }
  136. var cornerIdentifier: String {
  137. if self == .all {
  138. return ""
  139. }
  140. return "_corner(\(rawValue))"
  141. }
  142. }
  143. #if !os(macOS)
  144. /// Processor for adding an blend mode to images. Only CG-based images are supported.
  145. public struct BlendImageProcessor: ImageProcessor {
  146. /// Identifier of the processor.
  147. /// - Note: See documentation of `ImageProcessor` protocol for more.
  148. public let identifier: String
  149. /// Blend Mode will be used to blend the input image.
  150. public let blendMode: CGBlendMode
  151. /// Alpha will be used when blend image.
  152. public let alpha: CGFloat
  153. /// Background color of the output image. If `nil`, it will stay transparent.
  154. public let backgroundColor: Color?
  155. /// Initialize an `BlendImageProcessor`
  156. ///
  157. /// - parameter blendMode: Blend Mode will be used to blend the input image.
  158. /// - parameter alpha: Alpha will be used when blend image.
  159. /// From 0.0 to 1.0. 1.0 means solid image, 0.0 means transparent image.
  160. /// Default is 1.0.
  161. /// - parameter backgroundColor: Background color to apply for the output image. Default is `nil`.
  162. public init(blendMode: CGBlendMode, alpha: CGFloat = 1.0, backgroundColor: Color? = nil) {
  163. self.blendMode = blendMode
  164. self.alpha = alpha
  165. self.backgroundColor = backgroundColor
  166. var identifier = "com.onevcat.Kingfisher.BlendImageProcessor(\(blendMode.rawValue),\(alpha))"
  167. if let color = backgroundColor {
  168. identifier.append("_\(color.hex)")
  169. }
  170. self.identifier = identifier
  171. }
  172. /// Process an input `ImageProcessItem` item to an image for this processor.
  173. ///
  174. /// - parameter item: Input item which will be processed by `self`
  175. /// - parameter options: Options when processing the item.
  176. ///
  177. /// - returns: The processed image.
  178. ///
  179. /// - Note: See documentation of `ImageProcessor` protocol for more.
  180. public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
  181. switch item {
  182. case .image(let image):
  183. return image.kf.scaled(to: options.scaleFactor)
  184. .kf.image(withBlendMode: blendMode, alpha: alpha, backgroundColor: backgroundColor)
  185. case .data:
  186. return (DefaultImageProcessor.default >> self).process(item: item, options: options)
  187. }
  188. }
  189. }
  190. #endif
  191. #if os(macOS)
  192. /// Processor for adding an compositing operation to images. Only CG-based images are supported in macOS.
  193. public struct CompositingImageProcessor: ImageProcessor {
  194. /// Identifier of the processor.
  195. /// - Note: See documentation of `ImageProcessor` protocol for more.
  196. public let identifier: String
  197. /// Compositing operation will be used to the input image.
  198. public let compositingOperation: NSCompositingOperation
  199. /// Alpha will be used when compositing image.
  200. public let alpha: CGFloat
  201. /// Background color of the output image. If `nil`, it will stay transparent.
  202. public let backgroundColor: Color?
  203. /// Initialize an `CompositingImageProcessor`
  204. ///
  205. /// - parameter compositingOperation: Compositing operation will be used to the input image.
  206. /// - parameter alpha: Alpha will be used when compositing image.
  207. /// From 0.0 to 1.0. 1.0 means solid image, 0.0 means transparent image.
  208. /// Default is 1.0.
  209. /// - parameter backgroundColor: Background color to apply for the output image. Default is `nil`.
  210. public init(compositingOperation: NSCompositingOperation,
  211. alpha: CGFloat = 1.0,
  212. backgroundColor: Color? = nil)
  213. {
  214. self.compositingOperation = compositingOperation
  215. self.alpha = alpha
  216. self.backgroundColor = backgroundColor
  217. var identifier = "com.onevcat.Kingfisher.CompositingImageProcessor(\(compositingOperation.rawValue),\(alpha))"
  218. if let color = backgroundColor {
  219. identifier.append("_\(color.hex)")
  220. }
  221. self.identifier = identifier
  222. }
  223. /// Process an input `ImageProcessItem` item to an image for this processor.
  224. ///
  225. /// - parameter item: Input item which will be processed by `self`
  226. /// - parameter options: Options when processing the item.
  227. ///
  228. /// - returns: The processed image.
  229. ///
  230. /// - Note: See documentation of `ImageProcessor` protocol for more.
  231. public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
  232. switch item {
  233. case .image(let image):
  234. return image.kf.scaled(to: options.scaleFactor)
  235. .kf.image(withCompositingOperation: compositingOperation, alpha: alpha, backgroundColor: backgroundColor)
  236. case .data:
  237. return (DefaultImageProcessor.default >> self).process(item: item, options: options)
  238. }
  239. }
  240. }
  241. #endif
  242. /// Processor for making round corner images. Only CG-based images are supported in macOS,
  243. /// if a non-CG image passed in, the processor will do nothing.
  244. public struct RoundCornerImageProcessor: ImageProcessor {
  245. /// Identifier of the processor.
  246. /// - Note: See documentation of `ImageProcessor` protocol for more.
  247. public let identifier: String
  248. /// Corner radius will be applied in processing.
  249. public let cornerRadius: CGFloat
  250. /// The target corners which will be applied rounding.
  251. public let roundingCorners: RectCorner
  252. /// Target size of output image should be. If `nil`, the image will keep its original size after processing.
  253. public let targetSize: CGSize?
  254. /// Background color of the output image. If `nil`, it will stay transparent.
  255. public let backgroundColor: Color?
  256. /// Initialize a `RoundCornerImageProcessor`
  257. ///
  258. /// - parameter cornerRadius: Corner radius will be applied in processing.
  259. /// - parameter targetSize: Target size of output image should be. If `nil`,
  260. /// the image will keep its original size after processing.
  261. /// Default is `nil`.
  262. /// - parameter corners: The target corners which will be applied rounding. Default is `.all`.
  263. /// - parameter backgroundColor: Background color to apply for the output image. Default is `nil`.
  264. public init(cornerRadius: CGFloat, targetSize: CGSize? = nil, roundingCorners corners: RectCorner = .all, backgroundColor: Color? = nil) {
  265. self.cornerRadius = cornerRadius
  266. self.targetSize = targetSize
  267. self.roundingCorners = corners
  268. self.backgroundColor = backgroundColor
  269. self.identifier = {
  270. var identifier = ""
  271. if let size = targetSize {
  272. identifier = "com.onevcat.Kingfisher.RoundCornerImageProcessor(\(cornerRadius)_\(size)\(corners.cornerIdentifier))"
  273. } else {
  274. identifier = "com.onevcat.Kingfisher.RoundCornerImageProcessor(\(cornerRadius)\(corners.cornerIdentifier))"
  275. }
  276. if let backgroundColor = backgroundColor {
  277. identifier += "_\(backgroundColor)"
  278. }
  279. return identifier
  280. }()
  281. }
  282. /// Process an input `ImageProcessItem` item to an image for this processor.
  283. ///
  284. /// - parameter item: Input item which will be processed by `self`
  285. /// - parameter options: Options when processing the item.
  286. ///
  287. /// - returns: The processed image.
  288. ///
  289. /// - Note: See documentation of `ImageProcessor` protocol for more.
  290. public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
  291. switch item {
  292. case .image(let image):
  293. let size = targetSize ?? image.kf.size
  294. return image.kf.scaled(to: options.scaleFactor)
  295. .kf.image(withRoundRadius: cornerRadius, fit: size, roundingCorners: roundingCorners, backgroundColor: backgroundColor)
  296. case .data:
  297. return (DefaultImageProcessor.default >> self).process(item: item, options: options)
  298. }
  299. }
  300. }
  301. /// Specify how a size adjusts itself to fit a target size.
  302. ///
  303. /// - none: Not scale the content.
  304. /// - aspectFit: Scale the content to fit the size of the view by maintaining the aspect ratio.
  305. /// - aspectFill: Scale the content to fill the size of the view
  306. public enum ContentMode {
  307. case none
  308. case aspectFit
  309. case aspectFill
  310. }
  311. /// Processor for resizing images. Only CG-based images are supported in macOS.
  312. public struct ResizingImageProcessor: ImageProcessor {
  313. /// Identifier of the processor.
  314. /// - Note: See documentation of `ImageProcessor` protocol for more.
  315. public let identifier: String
  316. /// The reference size for resizing operation.
  317. public let referenceSize: CGSize
  318. /// Target content mode of output image should be.
  319. /// Default to ContentMode.none
  320. public let targetContentMode: ContentMode
  321. /// Initialize a `ResizingImageProcessor`.
  322. ///
  323. /// - Parameters:
  324. /// - referenceSize: The reference size for resizing operation.
  325. /// - mode: Target content mode of output image should be.
  326. ///
  327. /// - Note:
  328. /// The instance of `ResizingImageProcessor` will follow its `mode` property
  329. /// and try to resizing the input images to fit or fill the `referenceSize`.
  330. /// That means if you are using a `mode` besides of `.none`, you may get an
  331. /// image with its size not be the same as the `referenceSize`.
  332. ///
  333. /// **Example**: With input image size: {100, 200},
  334. /// `referenceSize`: {100, 100}, `mode`: `.aspectFit`,
  335. /// you will get an output image with size of {50, 100}, which "fit"s
  336. /// the `referenceSize`.
  337. ///
  338. /// If you need an output image exactly to be a specified size, append or use
  339. /// a `CroppingImageProcessor`.
  340. public init(referenceSize: CGSize, mode: ContentMode = .none) {
  341. self.referenceSize = referenceSize
  342. self.targetContentMode = mode
  343. if mode == .none {
  344. self.identifier = "com.onevcat.Kingfisher.ResizingImageProcessor(\(referenceSize))"
  345. } else {
  346. self.identifier = "com.onevcat.Kingfisher.ResizingImageProcessor(\(referenceSize), \(mode))"
  347. }
  348. }
  349. /// Process an input `ImageProcessItem` item to an image for this processor.
  350. ///
  351. /// - parameter item: Input item which will be processed by `self`
  352. /// - parameter options: Options when processing the item.
  353. ///
  354. /// - returns: The processed image.
  355. ///
  356. /// - Note: See documentation of `ImageProcessor` protocol for more.
  357. public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
  358. switch item {
  359. case .image(let image):
  360. return image.kf.scaled(to: options.scaleFactor)
  361. .kf.resize(to: referenceSize, for: targetContentMode)
  362. case .data:
  363. return (DefaultImageProcessor.default >> self).process(item: item, options: options)
  364. }
  365. }
  366. }
  367. /// Processor for adding blur effect to images. `Accelerate.framework` is used underhood for
  368. /// a better performance. A simulated Gaussian blur with specified blur radius will be applied.
  369. public struct BlurImageProcessor: ImageProcessor {
  370. /// Identifier of the processor.
  371. /// - Note: See documentation of `ImageProcessor` protocol for more.
  372. public let identifier: String
  373. /// Blur radius for the simulated Gaussian blur.
  374. public let blurRadius: CGFloat
  375. /// Initialize a `BlurImageProcessor`
  376. ///
  377. /// - parameter blurRadius: Blur radius for the simulated Gaussian blur.
  378. public init(blurRadius: CGFloat) {
  379. self.blurRadius = blurRadius
  380. self.identifier = "com.onevcat.Kingfisher.BlurImageProcessor(\(blurRadius))"
  381. }
  382. /// Process an input `ImageProcessItem` item to an image for this processor.
  383. ///
  384. /// - parameter item: Input item which will be processed by `self`
  385. /// - parameter options: Options when processing the item.
  386. ///
  387. /// - returns: The processed image.
  388. ///
  389. /// - Note: See documentation of `ImageProcessor` protocol for more.
  390. public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
  391. switch item {
  392. case .image(let image):
  393. let radius = blurRadius * options.scaleFactor
  394. return image.kf.scaled(to: options.scaleFactor)
  395. .kf.blurred(withRadius: radius)
  396. case .data:
  397. return (DefaultImageProcessor.default >> self).process(item: item, options: options)
  398. }
  399. }
  400. }
  401. /// Processor for adding an overlay to images. Only CG-based images are supported in macOS.
  402. public struct OverlayImageProcessor: ImageProcessor {
  403. /// Identifier of the processor.
  404. /// - Note: See documentation of `ImageProcessor` protocol for more.
  405. public let identifier: String
  406. /// Overlay color will be used to overlay the input image.
  407. public let overlay: Color
  408. /// Fraction will be used when overlay the color to image.
  409. public let fraction: CGFloat
  410. /// Initialize an `OverlayImageProcessor`
  411. ///
  412. /// - parameter overlay: Overlay color will be used to overlay the input image.
  413. /// - parameter fraction: Fraction will be used when overlay the color to image.
  414. /// From 0.0 to 1.0. 0.0 means solid color, 1.0 means transparent overlay.
  415. public init(overlay: Color, fraction: CGFloat = 0.5) {
  416. self.overlay = overlay
  417. self.fraction = fraction
  418. self.identifier = "com.onevcat.Kingfisher.OverlayImageProcessor(\(overlay.hex)_\(fraction))"
  419. }
  420. /// Process an input `ImageProcessItem` item to an image for this processor.
  421. ///
  422. /// - parameter item: Input item which will be processed by `self`
  423. /// - parameter options: Options when processing the item.
  424. ///
  425. /// - returns: The processed image.
  426. ///
  427. /// - Note: See documentation of `ImageProcessor` protocol for more.
  428. public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
  429. switch item {
  430. case .image(let image):
  431. return image.kf.scaled(to: options.scaleFactor)
  432. .kf.overlaying(with: overlay, fraction: fraction)
  433. case .data:
  434. return (DefaultImageProcessor.default >> self).process(item: item, options: options)
  435. }
  436. }
  437. }
  438. /// Processor for tint images with color. Only CG-based images are supported.
  439. public struct TintImageProcessor: ImageProcessor {
  440. /// Identifier of the processor.
  441. /// - Note: See documentation of `ImageProcessor` protocol for more.
  442. public let identifier: String
  443. /// Tint color will be used to tint the input image.
  444. public let tint: Color
  445. /// Initialize a `TintImageProcessor`
  446. ///
  447. /// - parameter tint: Tint color will be used to tint the input image.
  448. public init(tint: Color) {
  449. self.tint = tint
  450. self.identifier = "com.onevcat.Kingfisher.TintImageProcessor(\(tint.hex))"
  451. }
  452. /// Process an input `ImageProcessItem` item to an image for this processor.
  453. ///
  454. /// - parameter item: Input item which will be processed by `self`
  455. /// - parameter options: Options when processing the item.
  456. ///
  457. /// - returns: The processed image.
  458. ///
  459. /// - Note: See documentation of `ImageProcessor` protocol for more.
  460. public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
  461. switch item {
  462. case .image(let image):
  463. return image.kf.scaled(to: options.scaleFactor)
  464. .kf.tinted(with: tint)
  465. case .data:
  466. return (DefaultImageProcessor.default >> self).process(item: item, options: options)
  467. }
  468. }
  469. }
  470. /// Processor for applying some color control to images. Only CG-based images are supported.
  471. /// watchOS is not supported.
  472. public struct ColorControlsProcessor: ImageProcessor {
  473. /// Identifier of the processor.
  474. /// - Note: See documentation of `ImageProcessor` protocol for more.
  475. public let identifier: String
  476. /// Brightness changing to image.
  477. public let brightness: CGFloat
  478. /// Contrast changing to image.
  479. public let contrast: CGFloat
  480. /// Saturation changing to image.
  481. public let saturation: CGFloat
  482. /// InputEV changing to image.
  483. public let inputEV: CGFloat
  484. /// Initialize a `ColorControlsProcessor`
  485. ///
  486. /// - parameter brightness: Brightness changing to image.
  487. /// - parameter contrast: Contrast changing to image.
  488. /// - parameter saturation: Saturation changing to image.
  489. /// - parameter inputEV: InputEV changing to image.
  490. public init(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) {
  491. self.brightness = brightness
  492. self.contrast = contrast
  493. self.saturation = saturation
  494. self.inputEV = inputEV
  495. self.identifier = "com.onevcat.Kingfisher.ColorControlsProcessor(\(brightness)_\(contrast)_\(saturation)_\(inputEV))"
  496. }
  497. /// Process an input `ImageProcessItem` item to an image for this processor.
  498. ///
  499. /// - parameter item: Input item which will be processed by `self`
  500. /// - parameter options: Options when processing the item.
  501. ///
  502. /// - returns: The processed image.
  503. ///
  504. /// - Note: See documentation of `ImageProcessor` protocol for more.
  505. public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
  506. switch item {
  507. case .image(let image):
  508. return image.kf.scaled(to: options.scaleFactor)
  509. .kf.adjusted(brightness: brightness, contrast: contrast, saturation: saturation, inputEV: inputEV)
  510. case .data:
  511. return (DefaultImageProcessor.default >> self).process(item: item, options: options)
  512. }
  513. }
  514. }
  515. /// Processor for applying black and white effect to images. Only CG-based images are supported.
  516. /// watchOS is not supported.
  517. public struct BlackWhiteProcessor: ImageProcessor {
  518. /// Identifier of the processor.
  519. /// - Note: See documentation of `ImageProcessor` protocol for more.
  520. public let identifier = "com.onevcat.Kingfisher.BlackWhiteProcessor"
  521. /// Initialize a `BlackWhiteProcessor`
  522. public init() {}
  523. /// Process an input `ImageProcessItem` item to an image for this processor.
  524. ///
  525. /// - parameter item: Input item which will be processed by `self`
  526. /// - parameter options: Options when processing the item.
  527. ///
  528. /// - returns: The processed image.
  529. ///
  530. /// - Note: See documentation of `ImageProcessor` protocol for more.
  531. public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
  532. return ColorControlsProcessor(brightness: 0.0, contrast: 1.0, saturation: 0.0, inputEV: 0.7)
  533. .process(item: item, options: options)
  534. }
  535. }
  536. /// Processor for cropping an image. Only CG-based images are supported.
  537. /// watchOS is not supported.
  538. public struct CroppingImageProcessor: ImageProcessor {
  539. /// Identifier of the processor.
  540. /// - Note: See documentation of `ImageProcessor` protocol for more.
  541. public let identifier: String
  542. /// Target size of output image should be.
  543. public let size: CGSize
  544. /// Anchor point from which the output size should be calculate.
  545. /// The anchor point is consisted by two values between 0.0 and 1.0.
  546. /// It indicates a related point in current image.
  547. /// See `CroppingImageProcessor.init(size:anchor:)` for more.
  548. public let anchor: CGPoint
  549. /// Initialize a `CroppingImageProcessor`
  550. ///
  551. /// - Parameters:
  552. /// - size: Target size of output image should be.
  553. /// - anchor: The anchor point from which the size should be calculated.
  554. /// Default is `CGPoint(x: 0.5, y: 0.5)`, which means the center of input image.
  555. /// - Note:
  556. /// The anchor point is consisted by two values between 0.0 and 1.0.
  557. /// It indicates a related point in current image, eg: (0.0, 0.0) for top-left
  558. /// corner, (0.5, 0.5) for center and (1.0, 1.0) for bottom-right corner.
  559. /// The `size` property of `CroppingImageProcessor` will be used along with
  560. /// `anchor` to calculate a target rectangle in the size of image.
  561. ///
  562. /// The target size will be automatically calculated with a reasonable behavior.
  563. /// For example, when you have an image size of `CGSize(width: 100, height: 100)`,
  564. /// and a target size of `CGSize(width: 20, height: 20)`:
  565. /// - with a (0.0, 0.0) anchor (top-left), the crop rect will be `{0, 0, 20, 20}`;
  566. /// - with a (0.5, 0.5) anchor (center), it will be `{40, 40, 20, 20}`
  567. /// - while with a (1.0, 1.0) anchor (bottom-right), it will be `{80, 80, 20, 20}`
  568. public init(size: CGSize, anchor: CGPoint = CGPoint(x: 0.5, y: 0.5)) {
  569. self.size = size
  570. self.anchor = anchor
  571. self.identifier = "com.onevcat.Kingfisher.CroppingImageProcessor(\(size)_\(anchor))"
  572. }
  573. /// Process an input `ImageProcessItem` item to an image for this processor.
  574. ///
  575. /// - parameter item: Input item which will be processed by `self`
  576. /// - parameter options: Options when processing the item.
  577. ///
  578. /// - returns: The processed image.
  579. ///
  580. /// - Note: See documentation of `ImageProcessor` protocol for more.
  581. public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
  582. switch item {
  583. case .image(let image):
  584. return image.kf.scaled(to: options.scaleFactor)
  585. .kf.crop(to: size, anchorOn: anchor)
  586. case .data: return (DefaultImageProcessor.default >> self).process(item: item, options: options)
  587. }
  588. }
  589. }
  590. /// Concatenate two `ImageProcessor`s. `ImageProcessor.appen(another:)` is used internally.
  591. ///
  592. /// - parameter left: First processor.
  593. /// - parameter right: Second processor.
  594. ///
  595. /// - returns: The concatenated processor.
  596. public func >>(left: ImageProcessor, right: ImageProcessor) -> ImageProcessor {
  597. return left.append(another: right)
  598. }
  599. extension Color {
  600. var hex: String {
  601. var r: CGFloat = 0
  602. var g: CGFloat = 0
  603. var b: CGFloat = 0
  604. var a: CGFloat = 0
  605. #if os(macOS)
  606. (usingColorSpace(.sRGB) ?? self).getRed(&r, green: &g, blue: &b, alpha: &a)
  607. #else
  608. getRed(&r, green: &g, blue: &b, alpha: &a)
  609. #endif
  610. let rInt = Int(r * 255) << 24
  611. let gInt = Int(g * 255) << 16
  612. let bInt = Int(b * 255) << 8
  613. let aInt = Int(a * 255)
  614. let rgba = rInt | gInt | bInt | aInt
  615. return String(format:"#%08x", rgba)
  616. }
  617. }