ImageProcessor.swift 29 KB

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