ImageProcessor.swift 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922
  1. //
  2. // ImageProcessor.swift
  3. // Kingfisher
  4. //
  5. // Created by Wei Wang on 2016/08/26.
  6. //
  7. // Copyright (c) 2019 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) && !targetEnvironment(macCatalyst)
  29. import AppKit
  30. #else
  31. import UIKit
  32. #endif
  33. /// Represents an item which could be processed by an `ImageProcessor`.
  34. ///
  35. /// - image: Input image. The processor should provide a way to apply
  36. /// processing on this `image` and return the result image.
  37. /// - data: Input data. The processor should provide a way to apply
  38. /// processing on this `data` and return the result image.
  39. public enum ImageProcessItem {
  40. /// Input image. The processor should provide a way to apply
  41. /// processing on this `image` and return the result image.
  42. case image(KFCrossPlatformImage)
  43. /// Input data. The processor should provide a way to apply
  44. /// processing on this `data` and return the result image.
  45. case data(Data)
  46. }
  47. /// An `ImageProcessor` would be used to convert some downloaded data to an image.
  48. public protocol ImageProcessor {
  49. /// Identifier of the processor. It will be used to identify the processor when
  50. /// caching and retrieving an image. You might want to make sure that processors with
  51. /// same properties/functionality have the same identifiers, so correct processed images
  52. /// could be retrieved with proper key.
  53. ///
  54. /// - Note: Do not supply an empty string for a customized processor, which is already reserved by
  55. /// the `DefaultImageProcessor`. It is recommended to use a reverse domain name notation string of
  56. /// your own for the identifier.
  57. var identifier: String { get }
  58. /// Processes the input `ImageProcessItem` with this processor.
  59. ///
  60. /// - Parameters:
  61. /// - item: Input item which will be processed by `self`.
  62. /// - options: The parsed options when processing the item.
  63. /// - Returns: The processed image.
  64. ///
  65. /// - Note: The return value should be `nil` if processing failed while converting an input item to image.
  66. /// If `nil` received by the processing caller, an error will be reported and the process flow stops.
  67. /// If the processing flow is not critical for your flow, then when the input item is already an image
  68. /// (`.image` case) and there is any errors in the processing, you could return the input image itself
  69. /// to keep the processing pipeline continuing.
  70. /// - Note: Most processor only supports CG-based images. watchOS is not supported for processors containing
  71. /// a filter, the input image will be returned directly on watchOS.
  72. func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage?
  73. }
  74. extension ImageProcessor {
  75. /// Appends an `ImageProcessor` to another. The identifier of the new `ImageProcessor`
  76. /// will be "\(self.identifier)|>\(another.identifier)".
  77. ///
  78. /// - Parameter another: An `ImageProcessor` you want to append to `self`.
  79. /// - Returns: The new `ImageProcessor` will process the image in the order
  80. /// of the two processors concatenated.
  81. public func append(another: ImageProcessor) -> ImageProcessor {
  82. let newIdentifier = identifier.appending("|>\(another.identifier)")
  83. return GeneralProcessor(identifier: newIdentifier) {
  84. item, options in
  85. if let image = self.process(item: item, options: options) {
  86. return another.process(item: .image(image), options: options)
  87. } else {
  88. return nil
  89. }
  90. }
  91. }
  92. }
  93. func ==(left: ImageProcessor, right: ImageProcessor) -> Bool {
  94. return left.identifier == right.identifier
  95. }
  96. func !=(left: ImageProcessor, right: ImageProcessor) -> Bool {
  97. return !(left == right)
  98. }
  99. typealias ProcessorImp = ((ImageProcessItem, KingfisherParsedOptionsInfo) -> KFCrossPlatformImage?)
  100. struct GeneralProcessor: ImageProcessor {
  101. let identifier: String
  102. let p: ProcessorImp
  103. func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? {
  104. return p(item, options)
  105. }
  106. }
  107. /// The default processor. It converts the input data to a valid image.
  108. /// Images of .PNG, .JPEG and .GIF format are supported.
  109. /// If an image item is given as `.image` case, `DefaultImageProcessor` will
  110. /// do nothing on it and return the associated image.
  111. public struct DefaultImageProcessor: ImageProcessor {
  112. /// A default `DefaultImageProcessor` could be used across.
  113. public static let `default` = DefaultImageProcessor()
  114. /// Identifier of the processor.
  115. /// - Note: See documentation of `ImageProcessor` protocol for more.
  116. public let identifier = ""
  117. /// Creates a `DefaultImageProcessor`. Use `DefaultImageProcessor.default` to get an instance,
  118. /// if you do not have a good reason to create your own `DefaultImageProcessor`.
  119. public init() {}
  120. /// Processes the input `ImageProcessItem` with this processor.
  121. ///
  122. /// - Parameters:
  123. /// - item: Input item which will be processed by `self`.
  124. /// - options: Options when processing the item.
  125. /// - Returns: The processed image.
  126. ///
  127. /// - Note: See documentation of `ImageProcessor` protocol for more.
  128. public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? {
  129. switch item {
  130. case .image(let image):
  131. return image.kf.scaled(to: options.scaleFactor)
  132. case .data(let data):
  133. return KingfisherWrapper.image(data: data, options: options.imageCreatingOptions)
  134. }
  135. }
  136. }
  137. /// Represents the rect corner setting when processing a round corner image.
  138. public struct RectCorner: OptionSet {
  139. /// Raw value of the rect corner.
  140. public let rawValue: Int
  141. /// Represents the top left corner.
  142. public static let topLeft = RectCorner(rawValue: 1 << 0)
  143. /// Represents the top right corner.
  144. public static let topRight = RectCorner(rawValue: 1 << 1)
  145. /// Represents the bottom left corner.
  146. public static let bottomLeft = RectCorner(rawValue: 1 << 2)
  147. /// Represents the bottom right corner.
  148. public static let bottomRight = RectCorner(rawValue: 1 << 3)
  149. /// Represents all corners.
  150. public static let all: RectCorner = [.topLeft, .topRight, .bottomLeft, .bottomRight]
  151. /// Creates a `RectCorner` option set with a given value.
  152. ///
  153. /// - Parameter rawValue: The value represents a certain corner option.
  154. public init(rawValue: Int) {
  155. self.rawValue = rawValue
  156. }
  157. var cornerIdentifier: String {
  158. if self == .all {
  159. return ""
  160. }
  161. return "_corner(\(rawValue))"
  162. }
  163. }
  164. #if !os(macOS)
  165. /// Processor for adding an blend mode to images. Only CG-based images are supported.
  166. public struct BlendImageProcessor: ImageProcessor {
  167. /// Identifier of the processor.
  168. /// - Note: See documentation of `ImageProcessor` protocol for more.
  169. public let identifier: String
  170. /// Blend Mode will be used to blend the input image.
  171. public let blendMode: CGBlendMode
  172. /// Alpha will be used when blend image.
  173. public let alpha: CGFloat
  174. /// Background color of the output image. If `nil`, it will stay transparent.
  175. public let backgroundColor: KFCrossPlatformColor?
  176. /// Creates a `BlendImageProcessor`.
  177. ///
  178. /// - Parameters:
  179. /// - blendMode: Blend Mode will be used to blend the input image.
  180. /// - alpha: Alpha will be used when blend image. From 0.0 to 1.0. 1.0 means solid image,
  181. /// 0.0 means transparent image (not visible at all). Default is 1.0.
  182. /// - backgroundColor: Background color to apply for the output image. Default is `nil`.
  183. public init(blendMode: CGBlendMode, alpha: CGFloat = 1.0, backgroundColor: KFCrossPlatformColor? = nil) {
  184. self.blendMode = blendMode
  185. self.alpha = alpha
  186. self.backgroundColor = backgroundColor
  187. var identifier = "com.onevcat.Kingfisher.BlendImageProcessor(\(blendMode.rawValue),\(alpha))"
  188. if let color = backgroundColor {
  189. identifier.append("_\(color.rgbaDescription)")
  190. }
  191. self.identifier = identifier
  192. }
  193. /// Processes the input `ImageProcessItem` with this processor.
  194. ///
  195. /// - Parameters:
  196. /// - item: Input item which will be processed by `self`.
  197. /// - options: Options when processing the item.
  198. /// - Returns: The processed image.
  199. ///
  200. /// - Note: See documentation of `ImageProcessor` protocol for more.
  201. public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? {
  202. switch item {
  203. case .image(let image):
  204. return image.kf.scaled(to: options.scaleFactor)
  205. .kf.image(withBlendMode: blendMode, alpha: alpha, backgroundColor: backgroundColor)
  206. case .data:
  207. return (DefaultImageProcessor.default |> self).process(item: item, options: options)
  208. }
  209. }
  210. }
  211. #endif
  212. #if os(macOS)
  213. /// Processor for adding an compositing operation to images. Only CG-based images are supported in macOS.
  214. public struct CompositingImageProcessor: ImageProcessor {
  215. /// Identifier of the processor.
  216. /// - Note: See documentation of `ImageProcessor` protocol for more.
  217. public let identifier: String
  218. /// Compositing operation will be used to the input image.
  219. public let compositingOperation: NSCompositingOperation
  220. /// Alpha will be used when compositing image.
  221. public let alpha: CGFloat
  222. /// Background color of the output image. If `nil`, it will stay transparent.
  223. public let backgroundColor: KFCrossPlatformColor?
  224. /// Creates a `CompositingImageProcessor`
  225. ///
  226. /// - Parameters:
  227. /// - compositingOperation: Compositing operation will be used to the input image.
  228. /// - alpha: Alpha will be used when compositing image.
  229. /// From 0.0 to 1.0. 1.0 means solid image, 0.0 means transparent image.
  230. /// Default is 1.0.
  231. /// - backgroundColor: Background color to apply for the output image. Default is `nil`.
  232. public init(compositingOperation: NSCompositingOperation,
  233. alpha: CGFloat = 1.0,
  234. backgroundColor: KFCrossPlatformColor? = nil)
  235. {
  236. self.compositingOperation = compositingOperation
  237. self.alpha = alpha
  238. self.backgroundColor = backgroundColor
  239. var identifier = "com.onevcat.Kingfisher.CompositingImageProcessor(\(compositingOperation.rawValue),\(alpha))"
  240. if let color = backgroundColor {
  241. identifier.append("_\(color.rgbaDescription)")
  242. }
  243. self.identifier = identifier
  244. }
  245. /// Processes the input `ImageProcessItem` with this processor.
  246. ///
  247. /// - Parameters:
  248. /// - item: Input item which will be processed by `self`.
  249. /// - options: Options when processing the item.
  250. /// - Returns: The processed image.
  251. ///
  252. /// - Note: See documentation of `ImageProcessor` protocol for more.
  253. public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? {
  254. switch item {
  255. case .image(let image):
  256. return image.kf.scaled(to: options.scaleFactor)
  257. .kf.image(
  258. withCompositingOperation: compositingOperation,
  259. alpha: alpha,
  260. backgroundColor: backgroundColor)
  261. case .data:
  262. return (DefaultImageProcessor.default |> self).process(item: item, options: options)
  263. }
  264. }
  265. }
  266. #endif
  267. /// Represents a radius specified in a `RoundCornerImageProcessor`.
  268. public enum Radius {
  269. /// The radius should be calculated as a fraction of the image width. Typically the associated value should be
  270. /// between 0 and 0.5, where 0 represents no radius and 0.5 represents using half of the image width.
  271. case widthFraction(CGFloat)
  272. /// The radius should be calculated as a fraction of the image height. Typically the associated value should be
  273. /// between 0 and 0.5, where 0 represents no radius and 0.5 represents using half of the image height.
  274. case heightFraction(CGFloat)
  275. /// Use a fixed point value as the round corner radius.
  276. case point(CGFloat)
  277. var radiusIdentifier: String {
  278. switch self {
  279. case .widthFraction(let f):
  280. return "w_frac_\(f)"
  281. case .heightFraction(let f):
  282. return "h_frac_\(f)"
  283. case .point(let p):
  284. return p.description
  285. }
  286. }
  287. public func compute(with size: CGSize) -> CGFloat {
  288. let cornerRadius: CGFloat
  289. switch self {
  290. case .point(let point):
  291. cornerRadius = point
  292. case .widthFraction(let widthFraction):
  293. cornerRadius = size.width * widthFraction
  294. case .heightFraction(let heightFraction):
  295. cornerRadius = size.height * heightFraction
  296. }
  297. return cornerRadius
  298. }
  299. }
  300. /// Processor for making round corner images. Only CG-based images are supported in macOS,
  301. /// if a non-CG image passed in, the processor will do nothing.
  302. ///
  303. /// - Note: The input image will be rendered with round corner pixels removed. If the image itself does not contain
  304. /// alpha channel (for example, a JPEG image), the processed image will contain an alpha channel in memory in order
  305. /// to show correctly. However, when cached to disk, Kingfisher respects the original image format by default. That
  306. /// means the alpha channel will be removed for these images. When you load the processed image from cache again, you
  307. /// will lose transparent corner.
  308. ///
  309. /// You could use `FormatIndicatedCacheSerializer.png` to force Kingfisher to serialize the image to PNG format in this
  310. /// case.
  311. ///
  312. public struct RoundCornerImageProcessor: ImageProcessor {
  313. /// Identifier of the processor.
  314. /// - Note: See documentation of `ImageProcessor` protocol for more.
  315. public let identifier: String
  316. /// The radius will be applied in processing. Specify a certain point value with `.point`, or a fraction of the
  317. /// target image with `.widthFraction`. or `.heightFraction`. For example, given a square image with width and
  318. /// height equals, `.widthFraction(0.5)` means use half of the length of size and makes the final image a round one.
  319. public let radius: Radius
  320. /// The target corners which will be applied rounding.
  321. public let roundingCorners: RectCorner
  322. /// Target size of output image should be. If `nil`, the image will keep its original size after processing.
  323. public let targetSize: CGSize?
  324. /// Background color of the output image. If `nil`, it will use a transparent background.
  325. public let backgroundColor: KFCrossPlatformColor?
  326. /// Creates a `RoundCornerImageProcessor`.
  327. ///
  328. /// - Parameters:
  329. /// - cornerRadius: Corner radius in point will be applied in processing.
  330. /// - targetSize: Target size of output image should be. If `nil`,
  331. /// the image will keep its original size after processing.
  332. /// Default is `nil`.
  333. /// - corners: The target corners which will be applied rounding. Default is `.all`.
  334. /// - backgroundColor: Background color to apply for the output image. Default is `nil`.
  335. ///
  336. /// - Note:
  337. ///
  338. /// This initializer accepts a concrete point value for `cornerRadius`. If you do not know the image size, but still
  339. /// want to apply a full round-corner (making the final image a round one), or specify the corner radius as a
  340. /// fraction of one dimension of the target image, use the `Radius` version instead.
  341. ///
  342. public init(
  343. cornerRadius: CGFloat,
  344. targetSize: CGSize? = nil,
  345. roundingCorners corners: RectCorner = .all,
  346. backgroundColor: KFCrossPlatformColor? = nil
  347. )
  348. {
  349. let radius = Radius.point(cornerRadius)
  350. self.init(radius: radius, targetSize: targetSize, roundingCorners: corners, backgroundColor: backgroundColor)
  351. }
  352. /// Creates a `RoundCornerImageProcessor`.
  353. ///
  354. /// - Parameters:
  355. /// - radius: The radius will be applied in processing.
  356. /// - targetSize: Target size of output image should be. If `nil`,
  357. /// the image will keep its original size after processing.
  358. /// Default is `nil`.
  359. /// - corners: The target corners which will be applied rounding. Default is `.all`.
  360. /// - backgroundColor: Background color to apply for the output image. Default is `nil`.
  361. public init(
  362. radius: Radius,
  363. targetSize: CGSize? = nil,
  364. roundingCorners corners: RectCorner = .all,
  365. backgroundColor: KFCrossPlatformColor? = nil
  366. )
  367. {
  368. self.radius = radius
  369. self.targetSize = targetSize
  370. self.roundingCorners = corners
  371. self.backgroundColor = backgroundColor
  372. self.identifier = {
  373. var identifier = ""
  374. if let size = targetSize {
  375. identifier = "com.onevcat.Kingfisher.RoundCornerImageProcessor" +
  376. "(\(radius.radiusIdentifier)_\(size)\(corners.cornerIdentifier))"
  377. } else {
  378. identifier = "com.onevcat.Kingfisher.RoundCornerImageProcessor" +
  379. "(\(radius.radiusIdentifier)\(corners.cornerIdentifier))"
  380. }
  381. if let backgroundColor = backgroundColor {
  382. identifier += "_\(backgroundColor)"
  383. }
  384. return identifier
  385. }()
  386. }
  387. /// Processes the input `ImageProcessItem` with this processor.
  388. ///
  389. /// - Parameters:
  390. /// - item: Input item which will be processed by `self`.
  391. /// - options: Options when processing the item.
  392. /// - Returns: The processed image.
  393. ///
  394. /// - Note: See documentation of `ImageProcessor` protocol for more.
  395. public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? {
  396. switch item {
  397. case .image(let image):
  398. let size = targetSize ?? image.kf.size
  399. return image.kf.scaled(to: options.scaleFactor)
  400. .kf.image(
  401. withRadius: radius,
  402. fit: size,
  403. roundingCorners: roundingCorners,
  404. backgroundColor: backgroundColor)
  405. case .data:
  406. return (DefaultImageProcessor.default |> self).process(item: item, options: options)
  407. }
  408. }
  409. }
  410. public struct Border {
  411. public var color: KFCrossPlatformColor
  412. public var lineWidth: CGFloat
  413. /// The radius will be applied in processing. Specify a certain point value with `.point`, or a fraction of the
  414. /// target image with `.widthFraction`. or `.heightFraction`. For example, given a square image with width and
  415. /// height equals, `.widthFraction(0.5)` means use half of the length of size and makes the final image a round one.
  416. public var radius: Radius
  417. /// The target corners which will be applied rounding.
  418. public var roundingCorners: RectCorner
  419. public init(
  420. color: KFCrossPlatformColor = .black,
  421. lineWidth: CGFloat = 4,
  422. radius: Radius = .point(0),
  423. roundingCorners: RectCorner = .all
  424. ) {
  425. self.color = color
  426. self.lineWidth = lineWidth
  427. self.radius = radius
  428. self.roundingCorners = roundingCorners
  429. }
  430. var identifier: String {
  431. "\(color.rgbaDescription)_\(lineWidth)_\(radius.radiusIdentifier)_\(roundingCorners.cornerIdentifier)"
  432. }
  433. }
  434. public struct BorderImageProcessor: ImageProcessor {
  435. public var identifier: String { "com.onevcat.Kingfisher.RoundCornerImageProcessor(\(border)" }
  436. public let border: Border
  437. public init(border: Border) {
  438. self.border = border
  439. }
  440. public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? {
  441. switch item {
  442. case .image(let image):
  443. return image.kf.addingBorder(border)
  444. case .data:
  445. return (DefaultImageProcessor.default |> self).process(item: item, options: options)
  446. }
  447. }
  448. }
  449. /// Represents how a size adjusts itself to fit a target size.
  450. ///
  451. /// - none: Not scale the content.
  452. /// - aspectFit: Scales the content to fit the size of the view by maintaining the aspect ratio.
  453. /// - aspectFill: Scales the content to fill the size of the view.
  454. public enum ContentMode {
  455. /// Not scale the content.
  456. case none
  457. /// Scales the content to fit the size of the view by maintaining the aspect ratio.
  458. case aspectFit
  459. /// Scales the content to fill the size of the view.
  460. case aspectFill
  461. }
  462. /// Processor for resizing images.
  463. /// If you need to resize a data represented image to a smaller size, use `DownsamplingImageProcessor`
  464. /// instead, which is more efficient and uses less memory.
  465. public struct ResizingImageProcessor: ImageProcessor {
  466. /// Identifier of the processor.
  467. /// - Note: See documentation of `ImageProcessor` protocol for more.
  468. public let identifier: String
  469. /// The reference size for resizing operation in point.
  470. public let referenceSize: CGSize
  471. /// Target content mode of output image should be.
  472. /// Default is `.none`.
  473. public let targetContentMode: ContentMode
  474. /// Creates a `ResizingImageProcessor`.
  475. ///
  476. /// - Parameters:
  477. /// - referenceSize: The reference size for resizing operation in point.
  478. /// - mode: Target content mode of output image should be.
  479. ///
  480. /// - Note:
  481. /// The instance of `ResizingImageProcessor` will follow its `mode` property
  482. /// and try to resizing the input images to fit or fill the `referenceSize`.
  483. /// That means if you are using a `mode` besides of `.none`, you may get an
  484. /// image with its size not be the same as the `referenceSize`.
  485. ///
  486. /// **Example**: With input image size: {100, 200},
  487. /// `referenceSize`: {100, 100}, `mode`: `.aspectFit`,
  488. /// you will get an output image with size of {50, 100}, which "fit"s
  489. /// the `referenceSize`.
  490. ///
  491. /// If you need an output image exactly to be a specified size, append or use
  492. /// a `CroppingImageProcessor`.
  493. public init(referenceSize: CGSize, mode: ContentMode = .none) {
  494. self.referenceSize = referenceSize
  495. self.targetContentMode = mode
  496. if mode == .none {
  497. self.identifier = "com.onevcat.Kingfisher.ResizingImageProcessor(\(referenceSize))"
  498. } else {
  499. self.identifier = "com.onevcat.Kingfisher.ResizingImageProcessor(\(referenceSize), \(mode))"
  500. }
  501. }
  502. /// Processes the input `ImageProcessItem` with this processor.
  503. ///
  504. /// - Parameters:
  505. /// - item: Input item which will be processed by `self`.
  506. /// - options: Options when processing the item.
  507. /// - Returns: The processed image.
  508. ///
  509. /// - Note: See documentation of `ImageProcessor` protocol for more.
  510. public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? {
  511. switch item {
  512. case .image(let image):
  513. return image.kf.scaled(to: options.scaleFactor)
  514. .kf.resize(to: referenceSize, for: targetContentMode)
  515. case .data:
  516. return (DefaultImageProcessor.default |> self).process(item: item, options: options)
  517. }
  518. }
  519. }
  520. /// Processor for adding blur effect to images. `Accelerate.framework` is used underhood for
  521. /// a better performance. A simulated Gaussian blur with specified blur radius will be applied.
  522. public struct BlurImageProcessor: ImageProcessor {
  523. /// Identifier of the processor.
  524. /// - Note: See documentation of `ImageProcessor` protocol for more.
  525. public let identifier: String
  526. /// Blur radius for the simulated Gaussian blur.
  527. public let blurRadius: CGFloat
  528. /// Creates a `BlurImageProcessor`
  529. ///
  530. /// - parameter blurRadius: Blur radius for the simulated Gaussian blur.
  531. public init(blurRadius: CGFloat) {
  532. self.blurRadius = blurRadius
  533. self.identifier = "com.onevcat.Kingfisher.BlurImageProcessor(\(blurRadius))"
  534. }
  535. /// Processes the input `ImageProcessItem` with this processor.
  536. ///
  537. /// - Parameters:
  538. /// - item: Input item which will be processed by `self`.
  539. /// - options: Options when processing the item.
  540. /// - Returns: The processed image.
  541. ///
  542. /// - Note: See documentation of `ImageProcessor` protocol for more.
  543. public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? {
  544. switch item {
  545. case .image(let image):
  546. let radius = blurRadius * options.scaleFactor
  547. return image.kf.scaled(to: options.scaleFactor)
  548. .kf.blurred(withRadius: radius)
  549. case .data:
  550. return (DefaultImageProcessor.default |> self).process(item: item, options: options)
  551. }
  552. }
  553. }
  554. /// Processor for adding an overlay to images. Only CG-based images are supported in macOS.
  555. public struct OverlayImageProcessor: ImageProcessor {
  556. /// Identifier of the processor.
  557. /// - Note: See documentation of `ImageProcessor` protocol for more.
  558. public let identifier: String
  559. /// Overlay color will be used to overlay the input image.
  560. public let overlay: KFCrossPlatformColor
  561. /// Fraction will be used when overlay the color to image.
  562. public let fraction: CGFloat
  563. /// Creates an `OverlayImageProcessor`
  564. ///
  565. /// - parameter overlay: Overlay color will be used to overlay the input image.
  566. /// - parameter fraction: Fraction will be used when overlay the color to image.
  567. /// From 0.0 to 1.0. 0.0 means solid color, 1.0 means transparent overlay.
  568. public init(overlay: KFCrossPlatformColor, fraction: CGFloat = 0.5) {
  569. self.overlay = overlay
  570. self.fraction = fraction
  571. self.identifier = "com.onevcat.Kingfisher.OverlayImageProcessor(\(overlay.rgbaDescription)_\(fraction))"
  572. }
  573. /// Processes the input `ImageProcessItem` with this processor.
  574. ///
  575. /// - Parameters:
  576. /// - item: Input item which will be processed by `self`.
  577. /// - options: Options when processing the item.
  578. /// - Returns: The processed image.
  579. ///
  580. /// - Note: See documentation of `ImageProcessor` protocol for more.
  581. public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? {
  582. switch item {
  583. case .image(let image):
  584. return image.kf.scaled(to: options.scaleFactor)
  585. .kf.overlaying(with: overlay, fraction: fraction)
  586. case .data:
  587. return (DefaultImageProcessor.default |> self).process(item: item, options: options)
  588. }
  589. }
  590. }
  591. /// Processor for tint images with color. Only CG-based images are supported.
  592. public struct TintImageProcessor: ImageProcessor {
  593. /// Identifier of the processor.
  594. /// - Note: See documentation of `ImageProcessor` protocol for more.
  595. public let identifier: String
  596. /// Tint color will be used to tint the input image.
  597. public let tint: KFCrossPlatformColor
  598. /// Creates a `TintImageProcessor`
  599. ///
  600. /// - parameter tint: Tint color will be used to tint the input image.
  601. public init(tint: KFCrossPlatformColor) {
  602. self.tint = tint
  603. self.identifier = "com.onevcat.Kingfisher.TintImageProcessor(\(tint.rgbaDescription))"
  604. }
  605. /// Processes the input `ImageProcessItem` with this processor.
  606. ///
  607. /// - Parameters:
  608. /// - item: Input item which will be processed by `self`.
  609. /// - options: Options when processing the item.
  610. /// - Returns: The processed image.
  611. ///
  612. /// - Note: See documentation of `ImageProcessor` protocol for more.
  613. public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? {
  614. switch item {
  615. case .image(let image):
  616. return image.kf.scaled(to: options.scaleFactor)
  617. .kf.tinted(with: tint)
  618. case .data:
  619. return (DefaultImageProcessor.default |> self).process(item: item, options: options)
  620. }
  621. }
  622. }
  623. /// Processor for applying some color control to images. Only CG-based images are supported.
  624. /// watchOS is not supported.
  625. public struct ColorControlsProcessor: ImageProcessor {
  626. /// Identifier of the processor.
  627. /// - Note: See documentation of `ImageProcessor` protocol for more.
  628. public let identifier: String
  629. /// Brightness changing to image.
  630. public let brightness: CGFloat
  631. /// Contrast changing to image.
  632. public let contrast: CGFloat
  633. /// Saturation changing to image.
  634. public let saturation: CGFloat
  635. /// InputEV changing to image.
  636. public let inputEV: CGFloat
  637. /// Creates a `ColorControlsProcessor`
  638. ///
  639. /// - Parameters:
  640. /// - brightness: Brightness changing to image.
  641. /// - contrast: Contrast changing to image.
  642. /// - saturation: Saturation changing to image.
  643. /// - inputEV: InputEV changing to image.
  644. public init(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) {
  645. self.brightness = brightness
  646. self.contrast = contrast
  647. self.saturation = saturation
  648. self.inputEV = inputEV
  649. self.identifier = "com.onevcat.Kingfisher.ColorControlsProcessor(\(brightness)_\(contrast)_\(saturation)_\(inputEV))"
  650. }
  651. /// Processes the input `ImageProcessItem` with this processor.
  652. ///
  653. /// - Parameters:
  654. /// - item: Input item which will be processed by `self`.
  655. /// - options: Options when processing the item.
  656. /// - Returns: The processed image.
  657. ///
  658. /// - Note: See documentation of `ImageProcessor` protocol for more.
  659. public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? {
  660. switch item {
  661. case .image(let image):
  662. return image.kf.scaled(to: options.scaleFactor)
  663. .kf.adjusted(brightness: brightness, contrast: contrast, saturation: saturation, inputEV: inputEV)
  664. case .data:
  665. return (DefaultImageProcessor.default |> self).process(item: item, options: options)
  666. }
  667. }
  668. }
  669. /// Processor for applying black and white effect to images. Only CG-based images are supported.
  670. /// watchOS is not supported.
  671. public struct BlackWhiteProcessor: ImageProcessor {
  672. /// Identifier of the processor.
  673. /// - Note: See documentation of `ImageProcessor` protocol for more.
  674. public let identifier = "com.onevcat.Kingfisher.BlackWhiteProcessor"
  675. /// Creates a `BlackWhiteProcessor`
  676. public init() {}
  677. /// Processes the input `ImageProcessItem` with this processor.
  678. ///
  679. /// - Parameters:
  680. /// - item: Input item which will be processed by `self`.
  681. /// - options: Options when processing the item.
  682. /// - Returns: The processed image.
  683. ///
  684. /// - Note: See documentation of `ImageProcessor` protocol for more.
  685. public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? {
  686. return ColorControlsProcessor(brightness: 0.0, contrast: 1.0, saturation: 0.0, inputEV: 0.7)
  687. .process(item: item, options: options)
  688. }
  689. }
  690. /// Processor for cropping an image. Only CG-based images are supported.
  691. /// watchOS is not supported.
  692. public struct CroppingImageProcessor: ImageProcessor {
  693. /// Identifier of the processor.
  694. /// - Note: See documentation of `ImageProcessor` protocol for more.
  695. public let identifier: String
  696. /// Target size of output image should be.
  697. public let size: CGSize
  698. /// Anchor point from which the output size should be calculate.
  699. /// The anchor point is consisted by two values between 0.0 and 1.0.
  700. /// It indicates a related point in current image.
  701. /// See `CroppingImageProcessor.init(size:anchor:)` for more.
  702. public let anchor: CGPoint
  703. /// Creates a `CroppingImageProcessor`.
  704. ///
  705. /// - Parameters:
  706. /// - size: Target size of output image should be.
  707. /// - anchor: The anchor point from which the size should be calculated.
  708. /// Default is `CGPoint(x: 0.5, y: 0.5)`, which means the center of input image.
  709. /// - Note:
  710. /// The anchor point is consisted by two values between 0.0 and 1.0.
  711. /// It indicates a related point in current image, eg: (0.0, 0.0) for top-left
  712. /// corner, (0.5, 0.5) for center and (1.0, 1.0) for bottom-right corner.
  713. /// The `size` property of `CroppingImageProcessor` will be used along with
  714. /// `anchor` to calculate a target rectangle in the size of image.
  715. ///
  716. /// The target size will be automatically calculated with a reasonable behavior.
  717. /// For example, when you have an image size of `CGSize(width: 100, height: 100)`,
  718. /// and a target size of `CGSize(width: 20, height: 20)`:
  719. /// - with a (0.0, 0.0) anchor (top-left), the crop rect will be `{0, 0, 20, 20}`;
  720. /// - with a (0.5, 0.5) anchor (center), it will be `{40, 40, 20, 20}`
  721. /// - while with a (1.0, 1.0) anchor (bottom-right), it will be `{80, 80, 20, 20}`
  722. public init(size: CGSize, anchor: CGPoint = CGPoint(x: 0.5, y: 0.5)) {
  723. self.size = size
  724. self.anchor = anchor
  725. self.identifier = "com.onevcat.Kingfisher.CroppingImageProcessor(\(size)_\(anchor))"
  726. }
  727. /// Processes the input `ImageProcessItem` with this processor.
  728. ///
  729. /// - Parameters:
  730. /// - item: Input item which will be processed by `self`.
  731. /// - options: Options when processing the item.
  732. /// - Returns: The processed image.
  733. ///
  734. /// - Note: See documentation of `ImageProcessor` protocol for more.
  735. public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? {
  736. switch item {
  737. case .image(let image):
  738. return image.kf.scaled(to: options.scaleFactor)
  739. .kf.crop(to: size, anchorOn: anchor)
  740. case .data: return (DefaultImageProcessor.default |> self).process(item: item, options: options)
  741. }
  742. }
  743. }
  744. /// Processor for downsampling an image. Compared to `ResizingImageProcessor`, this processor
  745. /// does not render the images to resize. Instead, it downsamples the input data directly to an
  746. /// image. It is a more efficient than `ResizingImageProcessor`. Prefer to use `DownsamplingImageProcessor` as possible
  747. /// as you can than the `ResizingImageProcessor`.
  748. ///
  749. /// Only CG-based images are supported. Animated images (like GIF) is not supported.
  750. public struct DownsamplingImageProcessor: ImageProcessor {
  751. /// Target size of output image should be. It should be smaller than the size of
  752. /// input image. If it is larger, the result image will be the same size of input
  753. /// data without downsampling.
  754. public let size: CGSize
  755. /// Identifier of the processor.
  756. /// - Note: See documentation of `ImageProcessor` protocol for more.
  757. public let identifier: String
  758. /// Creates a `DownsamplingImageProcessor`.
  759. ///
  760. /// - Parameter size: The target size of the downsample operation.
  761. public init(size: CGSize) {
  762. self.size = size
  763. self.identifier = "com.onevcat.Kingfisher.DownsamplingImageProcessor(\(size))"
  764. }
  765. /// Processes the input `ImageProcessItem` with this processor.
  766. ///
  767. /// - Parameters:
  768. /// - item: Input item which will be processed by `self`.
  769. /// - options: Options when processing the item.
  770. /// - Returns: The processed image.
  771. ///
  772. /// - Note: See documentation of `ImageProcessor` protocol for more.
  773. public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? {
  774. switch item {
  775. case .image(let image):
  776. guard let data = image.kf.data(format: .unknown) else {
  777. return nil
  778. }
  779. return KingfisherWrapper.downsampledImage(data: data, to: size, scale: options.scaleFactor)
  780. case .data(let data):
  781. return KingfisherWrapper.downsampledImage(data: data, to: size, scale: options.scaleFactor)
  782. }
  783. }
  784. }
  785. infix operator |>: AdditionPrecedence
  786. public func |>(left: ImageProcessor, right: ImageProcessor) -> ImageProcessor {
  787. return left.append(another: right)
  788. }
  789. extension KFCrossPlatformColor {
  790. var rgba: (r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) {
  791. var r: CGFloat = 0
  792. var g: CGFloat = 0
  793. var b: CGFloat = 0
  794. var a: CGFloat = 0
  795. #if os(macOS)
  796. (usingColorSpace(.extendedSRGB) ?? self).getRed(&r, green: &g, blue: &b, alpha: &a)
  797. #else
  798. getRed(&r, green: &g, blue: &b, alpha: &a)
  799. #endif
  800. return (r, g, b, a)
  801. }
  802. var rgbaDescription: String {
  803. let components = self.rgba
  804. return String(format: "(%.2f,%.2f,%.2f,%.2f)", components.r, components.g, components.b, components.a)
  805. }
  806. }