ImageProcessor.swift 29 KB

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