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