ImageProcessor.swift 38 KB

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