Image.swift 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000
  1. //
  2. // Image.swift
  3. // Kingfisher
  4. //
  5. // Created by Wei Wang on 16/1/6.
  6. //
  7. // Copyright (c) 2018 Wei Wang <onevcat@gmail.com>
  8. //
  9. // Permission is hereby granted, free of charge, to any person obtaining a copy
  10. // of this software and associated documentation files (the "Software"), to deal
  11. // in the Software without restriction, including without limitation the rights
  12. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. // copies of the Software, and to permit persons to whom the Software is
  14. // furnished to do so, subject to the following conditions:
  15. //
  16. // The above copyright notice and this permission notice shall be included in
  17. // all copies or substantial portions of the Software.
  18. //
  19. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. // THE SOFTWARE.
  26. #if os(macOS)
  27. import AppKit
  28. private var imagesKey: Void?
  29. private var durationKey: Void?
  30. #else
  31. import UIKit
  32. import MobileCoreServices
  33. private var imageSourceKey: Void?
  34. #endif
  35. #if !os(watchOS)
  36. import Accelerate
  37. import CoreImage
  38. #endif
  39. private var animatedImageDataKey: Void?
  40. import ImageIO
  41. import CoreGraphics
  42. func getAssociatedObject<T>(_ object: Any, _ key: UnsafeRawPointer) -> T? {
  43. return objc_getAssociatedObject(object, key) as? T
  44. }
  45. func setRetainedAssociatedObject<T>(_ object: Any, _ key: UnsafeRawPointer, _ value: T) {
  46. objc_setAssociatedObject(object, key, value, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
  47. }
  48. // MARK: - Image Properties
  49. extension KingfisherClass where Base: Image {
  50. private(set) var animatedImageData: Data? {
  51. get { return getAssociatedObject(base, &animatedImageDataKey) }
  52. set { setRetainedAssociatedObject(base, &animatedImageDataKey, newValue) }
  53. }
  54. #if os(macOS)
  55. var cgImage: CGImage? {
  56. return base.cgImage(forProposedRect: nil, context: nil, hints: nil)
  57. }
  58. var scale: CGFloat {
  59. return 1.0
  60. }
  61. private(set) var images: [Image]? {
  62. get { return getAssociatedObject(base, &imagesKey) }
  63. set { setRetainedAssociatedObject(base, &imagesKey, newValue) }
  64. }
  65. private(set) var duration: TimeInterval {
  66. get { return getAssociatedObject(base, &durationKey) ?? 0.0 }
  67. set { setRetainedAssociatedObject(base, &durationKey, newValue) }
  68. }
  69. var size: CGSize {
  70. return base.representations.reduce(.zero) { size, rep in
  71. let width = max(size.width, CGFloat(rep.pixelsWide))
  72. let height = max(size.height, CGFloat(rep.pixelsHigh))
  73. return CGSize(width: width, height: height)
  74. }
  75. }
  76. #else
  77. var cgImage: CGImage? { return base.cgImage }
  78. var scale: CGFloat { return base.scale }
  79. var images: [Image]? { return base.images }
  80. var duration: TimeInterval { return base.duration }
  81. var size: CGSize { return base.size }
  82. private(set) var imageSource: CGImageSource? {
  83. get { return getAssociatedObject(base, &imageSourceKey) }
  84. set { setRetainedAssociatedObject(base, &imageSourceKey, newValue) }
  85. }
  86. #endif
  87. }
  88. // MARK: - Image Conversion
  89. extension KingfisherClass where Base: Image {
  90. #if os(macOS)
  91. static func image(cgImage: CGImage, scale: CGFloat, refImage: Image?) -> Image {
  92. return Image(cgImage: cgImage, size: .zero)
  93. }
  94. /// Normalize the image. This getter does nothing on macOS.
  95. public var normalized: Image { return base }
  96. #else
  97. /// Creating an image from a give `CGImage` at scale and orientation for refImage. The method signature is for
  98. /// compability of macOS version.
  99. static func image(cgImage: CGImage, scale: CGFloat, refImage: Image?) -> Image {
  100. return Image(cgImage: cgImage, scale: scale, orientation: refImage?.imageOrientation ?? .up)
  101. }
  102. /// Normalized image of current `base`.
  103. /// This method will try to redraw an image with orientation and scale considered.
  104. public var normalized: Image {
  105. // prevent animated image (GIF) lose it's images
  106. guard images == nil else { return base }
  107. // No need to do anything if already up
  108. guard base.imageOrientation != .up else { return base }
  109. return draw(to: size) {
  110. base.draw(in: CGRect(origin: .zero, size: size))
  111. }
  112. }
  113. static func animated(with images: [Image], forDuration duration: TimeInterval) -> Image? {
  114. return .animatedImage(with: images, duration: duration)
  115. }
  116. #endif
  117. }
  118. // MARK: - Image Representation
  119. extension KingfisherClass where Base: Image {
  120. // MARK: - PNG
  121. public func pngRepresentation() -> Data? {
  122. #if os(macOS)
  123. guard let cgimage = cgImage else {
  124. return nil
  125. }
  126. let rep = NSBitmapImageRep(cgImage: cgimage)
  127. return rep.representation(using: .png, properties: [:])
  128. #else
  129. return base.pngData()
  130. #endif
  131. }
  132. // MARK: - JPEG
  133. public func jpegRepresentation(compressionQuality: CGFloat) -> Data? {
  134. #if os(macOS)
  135. guard let cgImage = cgImage else {
  136. return nil
  137. }
  138. let rep = NSBitmapImageRep(cgImage: cgImage)
  139. return rep.representation(using:.jpeg, properties: [.compressionFactor: compressionQuality])
  140. #else
  141. return base.jpegData(compressionQuality: compressionQuality)
  142. #endif
  143. }
  144. // MARK: - GIF
  145. public func gifRepresentation() -> Data? {
  146. return animatedImageData
  147. }
  148. }
  149. public struct AnimatedImageCreatingOptions {
  150. public let scale: CGFloat
  151. public let duration: TimeInterval
  152. public let preloadAll: Bool
  153. public let onlyFirstFrame: Bool
  154. public init(
  155. scale: CGFloat = 1.0,
  156. duration: TimeInterval = 0.0,
  157. preloadAll: Bool = false,
  158. onlyFirstFrame: Bool = false)
  159. {
  160. self.scale = scale
  161. self.duration = duration
  162. self.preloadAll = preloadAll
  163. self.onlyFirstFrame = onlyFirstFrame
  164. }
  165. }
  166. class AnimatedImage {
  167. let images: [Image]
  168. let duration: TimeInterval
  169. init?(from imageSource: CGImageSource, for info: [String: Any], options: AnimatedImageCreatingOptions) {
  170. let frameCount = CGImageSourceGetCount(imageSource)
  171. var images = [Image]()
  172. var gifDuration = 0.0
  173. for i in 0 ..< frameCount {
  174. guard let imageRef = CGImageSourceCreateImageAtIndex(imageSource, i, info as CFDictionary) else {
  175. return nil
  176. }
  177. if frameCount == 1 {
  178. gifDuration = .infinity
  179. } else {
  180. // Get current animated GIF frame duration
  181. guard let properties = CGImageSourceCopyPropertiesAtIndex(imageSource, i, nil) else {
  182. return nil
  183. }
  184. let gifInfo = (properties as? [String: Any])?[kCGImagePropertyGIFDictionary as String] as? [String: Any]
  185. gifDuration += AnimatedImage.getFrameDuration(from: gifInfo)
  186. }
  187. images.append(KingfisherClass<Image>.image(cgImage: imageRef, scale: options.scale, refImage: nil))
  188. if options.onlyFirstFrame { break }
  189. }
  190. self.images = images
  191. self.duration = gifDuration
  192. }
  193. //Calculates frame duration for a gif frame out of the kCGImagePropertyGIFDictionary dictionary.
  194. static func getFrameDuration(from gifInfo: [String: Any]?) -> TimeInterval {
  195. let defaultFrameDuration = 0.1
  196. guard let gifInfo = gifInfo else { return defaultFrameDuration }
  197. let unclampedDelayTime = gifInfo[kCGImagePropertyGIFUnclampedDelayTime as String] as? NSNumber
  198. let delayTime = gifInfo[kCGImagePropertyGIFDelayTime as String] as? NSNumber
  199. let duration = unclampedDelayTime ?? delayTime
  200. guard let frameDuration = duration else { return defaultFrameDuration }
  201. return frameDuration.doubleValue > 0.011 ? frameDuration.doubleValue : defaultFrameDuration
  202. }
  203. }
  204. // MARK: - Create images from data
  205. extension KingfisherClass where Base: Image {
  206. public static func animated(with data: Data, options: AnimatedImageCreatingOptions) -> Image? {
  207. let info: [String: Any] = [
  208. kCGImageSourceShouldCache as String: true,
  209. kCGImageSourceTypeIdentifierHint as String: kUTTypeGIF
  210. ]
  211. guard let imageSource = CGImageSourceCreateWithData(data as CFData, info as CFDictionary) else {
  212. return nil
  213. }
  214. #if os(macOS)
  215. guard let animatedImage = AnimatedImage(from: imageSource, for: info, options: options) else {
  216. return nil
  217. }
  218. let image: Image?
  219. if options.onlyFirstFrame {
  220. image = animatedImage.images.first
  221. } else {
  222. image = Image(data: data)
  223. let kf = image?.kf
  224. kf?.images = animatedImage.images
  225. kf?.duration = animatedImage.duration
  226. }
  227. image?.kf.animatedImageData = data
  228. return image
  229. #else
  230. let image: Image?
  231. if options.preloadAll || options.onlyFirstFrame {
  232. // Use `images` image if you want to preload all animated data
  233. guard let animatedImage = AnimatedImage(from: imageSource, for: info, options: options) else {
  234. return nil
  235. }
  236. image = options.onlyFirstFrame ? animatedImage.images.first :
  237. KingfisherClass<Image>.animated(
  238. with: animatedImage.images,
  239. forDuration: options.duration <= 0.0 ? animatedImage.duration : options.duration)
  240. image?.kf.animatedImageData = data
  241. } else {
  242. image = Image(data: data)
  243. let kf = image?.kf
  244. kf?.imageSource = imageSource
  245. kf?.animatedImageData = data
  246. }
  247. return image
  248. #endif
  249. }
  250. @available(*, deprecated, message: "Pass parameters with `AnimatedImageCreatingOptions` instead.")
  251. public static func animated(
  252. with data: Data,
  253. scale: CGFloat = 1.0,
  254. duration: TimeInterval = 0.0,
  255. preloadAll: Bool,
  256. onlyFirstFrame: Bool = false) -> Image?
  257. {
  258. let options = AnimatedImageCreatingOptions(
  259. scale: scale, duration: duration, preloadAll: preloadAll, onlyFirstFrame: onlyFirstFrame)
  260. return animated(with: data, options: options)
  261. }
  262. public static func image(data: Data, scale: CGFloat, preloadAllAnimationData: Bool, onlyFirstFrame: Bool) -> Image? {
  263. var image: Image?
  264. #if os(macOS)
  265. switch data.kf.imageFormat {
  266. case .JPEG:
  267. image = Image(data: data)
  268. case .PNG:
  269. image = Image(data: data)
  270. case .GIF:
  271. let options = AnimatedImageCreatingOptions(
  272. scale: scale, duration: 0.0, preloadAll: preloadAllAnimationData, onlyFirstFrame: onlyFirstFrame)
  273. image = KingfisherClass<Image>.animated(with: data, options: options)
  274. case .unknown:
  275. image = Image(data: data)
  276. }
  277. #else
  278. switch data.kf.imageFormat {
  279. case .JPEG:
  280. image = Image(data: data, scale: scale)
  281. case .PNG:
  282. image = Image(data: data, scale: scale)
  283. case .GIF:
  284. let options = AnimatedImageCreatingOptions(
  285. scale: scale, duration: 0.0, preloadAll: preloadAllAnimationData, onlyFirstFrame: onlyFirstFrame)
  286. image = KingfisherClass<Image>.animated(with: data, options: options)
  287. case .unknown:
  288. image = Image(data: data, scale: scale)
  289. }
  290. #endif
  291. return image
  292. }
  293. }
  294. // MARK: - Image Transforming
  295. extension KingfisherClass where Base: Image {
  296. // MARK: - Blend Mode
  297. /// Create image based on `self` and apply blend mode.
  298. ///
  299. /// - parameter blendMode: The blend mode of creating image.
  300. /// - parameter alpha: The alpha should be used for image.
  301. /// - parameter backgroundColor: The background color for the output image.
  302. ///
  303. /// - returns: An image with blend mode applied.
  304. ///
  305. /// - Note: This method only works for CG-based image.
  306. #if !os(macOS)
  307. public func image(withBlendMode blendMode: CGBlendMode,
  308. alpha: CGFloat = 1.0,
  309. backgroundColor: Color? = nil) -> Image
  310. {
  311. guard let cgImage = cgImage else {
  312. assertionFailure("[Kingfisher] Blend mode image only works for CG-based image.")
  313. return base
  314. }
  315. let rect = CGRect(origin: .zero, size: size)
  316. return draw(cgImage: cgImage, to: rect.size) {
  317. if let backgroundColor = backgroundColor {
  318. backgroundColor.setFill()
  319. UIRectFill(rect)
  320. }
  321. base.draw(in: rect, blendMode: blendMode, alpha: alpha)
  322. }
  323. }
  324. #endif
  325. // MARK: - Compositing Operation
  326. /// Create image based on `self` and apply compositing operation.
  327. ///
  328. /// - parameter compositingOperation: The compositing operation of creating image.
  329. /// - parameter alpha: The alpha should be used for image.
  330. /// - parameter backgroundColor: The background color for the output image.
  331. ///
  332. /// - returns: An image with compositing operation applied.
  333. ///
  334. /// - Note: This method only works for CG-based image.
  335. #if os(macOS)
  336. public func image(withCompositingOperation compositingOperation: NSCompositingOperation,
  337. alpha: CGFloat = 1.0,
  338. backgroundColor: Color? = nil) -> Image
  339. {
  340. guard let cgImage = cgImage else {
  341. assertionFailure("[Kingfisher] Compositing Operation image only works for CG-based image.")
  342. return base
  343. }
  344. let rect = CGRect(origin: .zero, size: size)
  345. return draw(cgImage: cgImage, to: rect.size) {
  346. if let backgroundColor = backgroundColor {
  347. backgroundColor.setFill()
  348. rect.fill()
  349. }
  350. base.draw(in: rect, from: NSRect.zero, operation: compositingOperation, fraction: alpha)
  351. }
  352. }
  353. #endif
  354. // MARK: - Round Corner
  355. /// Create a round corner image based on `self`.
  356. ///
  357. /// - parameter radius: The round corner radius of creating image.
  358. /// - parameter size: The target size of creating image.
  359. /// - parameter corners: The target corners which will be applied rounding.
  360. /// - parameter backgroundColor: The background color for the output image
  361. ///
  362. /// - returns: An image with round corner of `self`.
  363. ///
  364. /// - Note: This method only works for CG-based image.
  365. public func image(withRoundRadius radius: CGFloat,
  366. fit size: CGSize,
  367. roundingCorners corners: RectCorner = .all,
  368. backgroundColor: Color? = nil) -> Image
  369. {
  370. guard let cgImage = cgImage else {
  371. assertionFailure("[Kingfisher] Round corner image only works for CG-based image.")
  372. return base
  373. }
  374. let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
  375. return draw(cgImage: cgImage, to: size) {
  376. #if os(macOS)
  377. if let backgroundColor = backgroundColor {
  378. let rectPath = NSBezierPath(rect: rect)
  379. backgroundColor.setFill()
  380. rectPath.fill()
  381. }
  382. let path = NSBezierPath(roundedRect: rect, byRoundingCorners: corners, radius: radius)
  383. path.windingRule = .evenOdd
  384. path.addClip()
  385. base.draw(in: rect)
  386. #else
  387. guard let context = UIGraphicsGetCurrentContext() else {
  388. assertionFailure("[Kingfisher] Failed to create CG context for image.")
  389. return
  390. }
  391. if let backgroundColor = backgroundColor {
  392. let rectPath = UIBezierPath(rect: rect)
  393. backgroundColor.setFill()
  394. rectPath.fill()
  395. }
  396. let path = UIBezierPath(roundedRect: rect,
  397. byRoundingCorners: corners.uiRectCorner,
  398. cornerRadii: CGSize(width: radius, height: radius)).cgPath
  399. context.addPath(path)
  400. context.clip()
  401. base.draw(in: rect)
  402. #endif
  403. }
  404. }
  405. #if os(iOS) || os(tvOS)
  406. func resize(to size: CGSize, for contentMode: UIView.ContentMode) -> Image {
  407. switch contentMode {
  408. case .scaleAspectFit:
  409. return resize(to: size, for: .aspectFit)
  410. case .scaleAspectFill:
  411. return resize(to: size, for: .aspectFill)
  412. default:
  413. return resize(to: size)
  414. }
  415. }
  416. #endif
  417. // MARK: - Resize
  418. /// Resize `self` to an image of new size.
  419. ///
  420. /// - parameter size: The target size.
  421. ///
  422. /// - returns: An image with new size.
  423. ///
  424. /// - Note: This method only works for CG-based image.
  425. public func resize(to size: CGSize) -> Image {
  426. guard let cgImage = cgImage else {
  427. assertionFailure("[Kingfisher] Resize only works for CG-based image.")
  428. return base
  429. }
  430. let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
  431. return draw(cgImage: cgImage, to: size) {
  432. #if os(macOS)
  433. base.draw(in: rect, from: NSRect.zero, operation: .copy, fraction: 1.0)
  434. #else
  435. base.draw(in: rect)
  436. #endif
  437. }
  438. }
  439. /// Resize `self` to an image of new size, respecting the content mode.
  440. ///
  441. /// - Parameters:
  442. /// - size: The target size.
  443. /// - contentMode: Content mode of output image should be.
  444. /// - Returns: An image with new size.
  445. public func resize(to size: CGSize, for contentMode: ContentMode) -> Image {
  446. switch contentMode {
  447. case .aspectFit:
  448. let newSize = self.size.kf.constrained(size)
  449. return resize(to: newSize)
  450. case .aspectFill:
  451. let newSize = self.size.kf.filling(size)
  452. return resize(to: newSize)
  453. default:
  454. return resize(to: size)
  455. }
  456. }
  457. public func crop(to size: CGSize, anchorOn anchor: CGPoint) -> Image {
  458. guard let cgImage = cgImage else {
  459. assertionFailure("[Kingfisher] Crop only works for CG-based image.")
  460. return base
  461. }
  462. let rect = self.size.kf.constrainedRect(for: size, anchor: anchor)
  463. guard let image = cgImage.cropping(to: rect.scaled(scale)) else {
  464. assertionFailure("[Kingfisher] Cropping image failed.")
  465. return base
  466. }
  467. return KingfisherClass.image(cgImage: image, scale: scale, refImage: base)
  468. }
  469. // MARK: - Blur
  470. /// Create an image with blur effect based on `self`.
  471. ///
  472. /// - parameter radius: The blur radius should be used when creating blur effect.
  473. ///
  474. /// - returns: An image with blur effect applied.
  475. ///
  476. /// - Note: This method only works for CG-based image.
  477. public func blurred(withRadius radius: CGFloat) -> Image {
  478. #if os(watchOS)
  479. return base
  480. #else
  481. guard let cgImage = cgImage else {
  482. assertionFailure("[Kingfisher] Blur only works for CG-based image.")
  483. return base
  484. }
  485. // http://www.w3.org/TR/SVG/filters.html#feGaussianBlurElement
  486. // let d = floor(s * 3*sqrt(2*pi)/4 + 0.5)
  487. // if d is odd, use three box-blurs of size 'd', centered on the output pixel.
  488. let s = Float(max(radius, 2.0))
  489. // We will do blur on a resized image (*0.5), so the blur radius could be half as well.
  490. // Fix the slow compiling time for Swift 3.
  491. // See https://github.com/onevcat/Kingfisher/issues/611
  492. let pi2 = 2 * Float.pi
  493. let sqrtPi2 = sqrt(pi2)
  494. var targetRadius = floor(s * 3.0 * sqrtPi2 / 4.0 + 0.5)
  495. if targetRadius.isEven {
  496. targetRadius += 1
  497. }
  498. let iterations: Int
  499. if radius < 0.5 {
  500. iterations = 1
  501. } else if radius < 1.5 {
  502. iterations = 2
  503. } else {
  504. iterations = 3
  505. }
  506. let w = Int(size.width)
  507. let h = Int(size.height)
  508. let rowBytes = Int(CGFloat(cgImage.bytesPerRow))
  509. func createEffectBuffer(_ context: CGContext) -> vImage_Buffer {
  510. let data = context.data
  511. let width = vImagePixelCount(context.width)
  512. let height = vImagePixelCount(context.height)
  513. let rowBytes = context.bytesPerRow
  514. return vImage_Buffer(data: data, height: height, width: width, rowBytes: rowBytes)
  515. }
  516. guard let context = beginContext(size: size, scale: scale) else {
  517. assertionFailure("[Kingfisher] Failed to create CG context for blurring image.")
  518. return base
  519. }
  520. defer { endContext() }
  521. context.draw(cgImage, in: CGRect(x: 0, y: 0, width: w, height: h))
  522. var inBuffer = createEffectBuffer(context)
  523. guard let outContext = beginContext(size: size, scale: scale) else {
  524. assertionFailure("[Kingfisher] Failed to create CG context for blurring image.")
  525. return base
  526. }
  527. defer { endContext() }
  528. var outBuffer = createEffectBuffer(outContext)
  529. for _ in 0 ..< iterations {
  530. vImageBoxConvolve_ARGB8888(&inBuffer, &outBuffer, nil, 0, 0, UInt32(targetRadius), UInt32(targetRadius), nil, vImage_Flags(kvImageEdgeExtend))
  531. (inBuffer, outBuffer) = (outBuffer, inBuffer)
  532. }
  533. #if os(macOS)
  534. let result = outContext.makeImage().flatMap { fixedForRetinaPixel(cgImage: $0, to: size) }
  535. #else
  536. let result = outContext.makeImage().flatMap { Image(cgImage: $0, scale: base.scale, orientation: base.imageOrientation) }
  537. #endif
  538. guard let blurredImage = result else {
  539. assertionFailure("[Kingfisher] Can not make an blurred image within this context.")
  540. return base
  541. }
  542. return blurredImage
  543. #endif
  544. }
  545. // MARK: - Overlay
  546. /// Create an image from `self` with a color overlay layer.
  547. ///
  548. /// - parameter color: The color should be use to overlay.
  549. /// - parameter fraction: Fraction of input color. From 0.0 to 1.0. 0.0 means solid color, 1.0 means transparent overlay.
  550. ///
  551. /// - returns: An image with a color overlay applied.
  552. ///
  553. /// - Note: This method only works for CG-based image.
  554. public func overlaying(with color: Color, fraction: CGFloat) -> Image {
  555. guard let cgImage = cgImage else {
  556. assertionFailure("[Kingfisher] Overlaying only works for CG-based image.")
  557. return base
  558. }
  559. let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
  560. return draw(cgImage: cgImage, to: rect.size) {
  561. #if os(macOS)
  562. base.draw(in: rect)
  563. if fraction > 0 {
  564. color.withAlphaComponent(1 - fraction).set()
  565. rect.fill(using: .sourceAtop)
  566. }
  567. #else
  568. color.set()
  569. UIRectFill(rect)
  570. base.draw(in: rect, blendMode: .destinationIn, alpha: 1.0)
  571. if fraction > 0 {
  572. base.draw(in: rect, blendMode: .sourceAtop, alpha: fraction)
  573. }
  574. #endif
  575. }
  576. }
  577. // MARK: - Tint
  578. /// Create an image from `self` with a color tint.
  579. ///
  580. /// - parameter color: The color should be used to tint `self`
  581. ///
  582. /// - returns: An image with a color tint applied.
  583. public func tinted(with color: Color) -> Image {
  584. #if os(watchOS)
  585. return base
  586. #else
  587. return apply(.tint(color))
  588. #endif
  589. }
  590. // MARK: - Color Control
  591. /// Create an image from `self` with color control.
  592. ///
  593. /// - parameter brightness: Brightness changing to image.
  594. /// - parameter contrast: Contrast changing to image.
  595. /// - parameter saturation: Saturation changing to image.
  596. /// - parameter inputEV: InputEV changing to image.
  597. ///
  598. /// - returns: An image with color control applied.
  599. public func adjusted(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) -> Image {
  600. #if os(watchOS)
  601. return base
  602. #else
  603. return apply(.colorControl((brightness, contrast, saturation, inputEV)))
  604. #endif
  605. }
  606. /// Return an image with given scale.
  607. ///
  608. /// - Parameter scale: Target scale factor the new image should have.
  609. /// - Returns: The image with target scale. If the base image is already in the scale, `base` will be returned.
  610. public func scaled(to scale: CGFloat) -> Image {
  611. guard scale != self.scale else {
  612. return base
  613. }
  614. guard let cgImage = cgImage else {
  615. assertionFailure("[Kingfisher] Scaling only works for CG-based image.")
  616. return base
  617. }
  618. return KingfisherClass.image(cgImage: cgImage, scale: scale, refImage: base)
  619. }
  620. }
  621. // MARK: - Decode
  622. extension KingfisherClass where Base: Image {
  623. public var decoded: Image {
  624. return decoded(scale: scale)
  625. }
  626. public func decoded(scale: CGFloat) -> Image {
  627. // prevent animated image (GIF) lose it's images
  628. #if os(iOS)
  629. if imageSource != nil { return base }
  630. #else
  631. if images != nil { return base }
  632. #endif
  633. guard let imageRef = self.cgImage else {
  634. assertionFailure("[Kingfisher] Decoding only works for CG-based image.")
  635. return base
  636. }
  637. // Draw CGImage in a plain context with scale of 1.0.
  638. guard let context = beginContext(size: CGSize(width: imageRef.width, height: imageRef.height), scale: 1.0) else {
  639. assertionFailure("[Kingfisher] Decoding fails to create a valid context.")
  640. return base
  641. }
  642. defer { endContext() }
  643. let rect = CGRect(x: 0, y: 0, width: CGFloat(imageRef.width), height: CGFloat(imageRef.height))
  644. context.draw(imageRef, in: rect)
  645. let decompressedImageRef = context.makeImage()
  646. return KingfisherClass<Image>.image(cgImage: decompressedImageRef!, scale: scale, refImage: base)
  647. }
  648. }
  649. // MARK: - Image format
  650. private struct ImageHeaderData {
  651. static var PNG: [UInt8] = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]
  652. static var JPEG_SOI: [UInt8] = [0xFF, 0xD8]
  653. static var JPEG_IF: [UInt8] = [0xFF]
  654. static var GIF: [UInt8] = [0x47, 0x49, 0x46]
  655. }
  656. public enum ImageFormat {
  657. case unknown, PNG, JPEG, GIF
  658. }
  659. // MARK: - Misc Helpers
  660. extension Data: KingfisherStructCompatible {}
  661. extension KingfisherStruct where Base == Data {
  662. public var imageFormat: ImageFormat {
  663. var buffer = [UInt8](repeating: 0, count: 8)
  664. (base as NSData).getBytes(&buffer, length: 8)
  665. if buffer == ImageHeaderData.PNG {
  666. return .PNG
  667. } else if buffer[0] == ImageHeaderData.JPEG_SOI[0] &&
  668. buffer[1] == ImageHeaderData.JPEG_SOI[1] &&
  669. buffer[2] == ImageHeaderData.JPEG_IF[0]
  670. {
  671. return .JPEG
  672. } else if buffer[0] == ImageHeaderData.GIF[0] &&
  673. buffer[1] == ImageHeaderData.GIF[1] &&
  674. buffer[2] == ImageHeaderData.GIF[2]
  675. {
  676. return .GIF
  677. }
  678. return .unknown
  679. }
  680. }
  681. extension CGSize: KingfisherStructCompatible {}
  682. extension KingfisherStruct where Base == CGSize {
  683. public func resize(to size: CGSize, for contentMode: ContentMode) -> CGSize {
  684. switch contentMode {
  685. case .aspectFit:
  686. return constrained(size)
  687. case .aspectFill:
  688. return filling(size)
  689. default:
  690. return self.base
  691. }
  692. }
  693. public func constrained(_ size: CGSize) -> CGSize {
  694. let aspectWidth = round(aspectRatio * size.height)
  695. let aspectHeight = round(size.width / aspectRatio)
  696. return aspectWidth > size.width ? CGSize(width: size.width, height: aspectHeight) : CGSize(width: aspectWidth, height: size.height)
  697. }
  698. public func filling(_ size: CGSize) -> CGSize {
  699. let aspectWidth = round(aspectRatio * size.height)
  700. let aspectHeight = round(size.width / aspectRatio)
  701. return aspectWidth < size.width ? CGSize(width: size.width, height: aspectHeight) : CGSize(width: aspectWidth, height: size.height)
  702. }
  703. private var aspectRatio: CGFloat {
  704. return base.height == 0.0 ? 1.0 : base.width / base.height
  705. }
  706. public func constrainedRect(for size: CGSize, anchor: CGPoint) -> CGRect {
  707. let unifiedAnchor = CGPoint(x: anchor.x.clamped(to: 0.0...1.0),
  708. y: anchor.y.clamped(to: 0.0...1.0))
  709. let x = unifiedAnchor.x * base.width - unifiedAnchor.x * size.width
  710. let y = unifiedAnchor.y * base.height - unifiedAnchor.y * size.height
  711. let r = CGRect(x: x, y: y, width: size.width, height: size.height)
  712. let ori = CGRect(origin: CGPoint.zero, size: base)
  713. return ori.intersection(r)
  714. }
  715. }
  716. extension CGRect {
  717. func scaled(_ scale: CGFloat) -> CGRect {
  718. return CGRect(x: origin.x * scale, y: origin.y * scale,
  719. width: size.width * scale, height: size.height * scale)
  720. }
  721. }
  722. extension Comparable {
  723. func clamped(to limits: ClosedRange<Self>) -> Self {
  724. return min(max(self, limits.lowerBound), limits.upperBound)
  725. }
  726. }
  727. extension KingfisherClass where Base: Image {
  728. func beginContext(size: CGSize, scale: CGFloat) -> CGContext? {
  729. #if os(macOS)
  730. guard let rep = NSBitmapImageRep(
  731. bitmapDataPlanes: nil,
  732. pixelsWide: Int(size.width),
  733. pixelsHigh: Int(size.height),
  734. bitsPerSample: cgImage?.bitsPerComponent ?? 8,
  735. samplesPerPixel: 4,
  736. hasAlpha: true,
  737. isPlanar: false,
  738. colorSpaceName: .calibratedRGB,
  739. bytesPerRow: 0,
  740. bitsPerPixel: 0) else
  741. {
  742. assertionFailure("[Kingfisher] Image representation cannot be created.")
  743. return nil
  744. }
  745. rep.size = size
  746. NSGraphicsContext.saveGraphicsState()
  747. guard let context = NSGraphicsContext(bitmapImageRep: rep) else {
  748. assertionFailure("[Kingfisher] Image contenxt cannot be created.")
  749. return nil
  750. }
  751. NSGraphicsContext.current = context
  752. return context.cgContext
  753. #else
  754. UIGraphicsBeginImageContextWithOptions(size, false, scale)
  755. let context = UIGraphicsGetCurrentContext()
  756. context?.scaleBy(x: 1.0, y: -1.0)
  757. context?.translateBy(x: 0, y: -size.height)
  758. return context
  759. #endif
  760. }
  761. func endContext() {
  762. #if os(macOS)
  763. NSGraphicsContext.restoreGraphicsState()
  764. #else
  765. UIGraphicsEndImageContext()
  766. #endif
  767. }
  768. func draw(cgImage: CGImage? = nil, to size: CGSize, draw: ()->()) -> Image {
  769. #if os(macOS)
  770. guard let rep = NSBitmapImageRep(
  771. bitmapDataPlanes: nil,
  772. pixelsWide: Int(size.width),
  773. pixelsHigh: Int(size.height),
  774. bitsPerSample: cgImage?.bitsPerComponent ?? 8,
  775. samplesPerPixel: 4,
  776. hasAlpha: true,
  777. isPlanar: false,
  778. colorSpaceName: .calibratedRGB,
  779. bytesPerRow: 0,
  780. bitsPerPixel: 0) else
  781. {
  782. assertionFailure("[Kingfisher] Image representation cannot be created.")
  783. return base
  784. }
  785. rep.size = size
  786. NSGraphicsContext.saveGraphicsState()
  787. let context = NSGraphicsContext(bitmapImageRep: rep)
  788. NSGraphicsContext.current = context
  789. draw()
  790. NSGraphicsContext.restoreGraphicsState()
  791. let outputImage = Image(size: size)
  792. outputImage.addRepresentation(rep)
  793. return outputImage
  794. #else
  795. UIGraphicsBeginImageContextWithOptions(size, false, scale)
  796. defer { UIGraphicsEndImageContext() }
  797. draw()
  798. return UIGraphicsGetImageFromCurrentImageContext() ?? base
  799. #endif
  800. }
  801. #if os(macOS)
  802. func fixedForRetinaPixel(cgImage: CGImage, to size: CGSize) -> Image {
  803. let image = Image(cgImage: cgImage, size: base.size)
  804. let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
  805. return draw(cgImage: cgImage, to: self.size) {
  806. image.draw(in: rect, from: NSRect.zero, operation: .copy, fraction: 1.0)
  807. }
  808. }
  809. #endif
  810. }
  811. extension Float {
  812. var isEven: Bool {
  813. return truncatingRemainder(dividingBy: 2.0) == 0
  814. }
  815. }
  816. #if os(macOS)
  817. extension NSBezierPath {
  818. convenience init(roundedRect rect: NSRect, topLeftRadius: CGFloat, topRightRadius: CGFloat,
  819. bottomLeftRadius: CGFloat, bottomRightRadius: CGFloat)
  820. {
  821. self.init()
  822. let maxCorner = min(rect.width, rect.height) / 2
  823. let radiusTopLeft = min(maxCorner, max(0, topLeftRadius))
  824. let radiusTopRight = min(maxCorner, max(0, topRightRadius))
  825. let radiusBottomLeft = min(maxCorner, max(0, bottomLeftRadius))
  826. let radiusBottomRight = min(maxCorner, max(0, bottomRightRadius))
  827. guard !NSIsEmptyRect(rect) else {
  828. return
  829. }
  830. let topLeft = NSMakePoint(NSMinX(rect), NSMaxY(rect));
  831. let topRight = NSMakePoint(NSMaxX(rect), NSMaxY(rect));
  832. let bottomRight = NSMakePoint(NSMaxX(rect), NSMinY(rect));
  833. move(to: NSMakePoint(NSMidX(rect), NSMaxY(rect)))
  834. appendArc(from: topLeft, to: rect.origin, radius: radiusTopLeft)
  835. appendArc(from: rect.origin, to: bottomRight, radius: radiusBottomLeft)
  836. appendArc(from: bottomRight, to: topRight, radius: radiusBottomRight)
  837. appendArc(from: topRight, to: topLeft, radius: radiusTopRight)
  838. close()
  839. }
  840. convenience init(roundedRect rect: NSRect, byRoundingCorners corners: RectCorner, radius: CGFloat) {
  841. let radiusTopLeft = corners.contains(.topLeft) ? radius : 0
  842. let radiusTopRight = corners.contains(.topRight) ? radius : 0
  843. let radiusBottomLeft = corners.contains(.bottomLeft) ? radius : 0
  844. let radiusBottomRight = corners.contains(.bottomRight) ? radius : 0
  845. self.init(roundedRect: rect, topLeftRadius: radiusTopLeft, topRightRadius: radiusTopRight,
  846. bottomLeftRadius: radiusBottomLeft, bottomRightRadius: radiusBottomRight)
  847. }
  848. }
  849. #else
  850. extension RectCorner {
  851. var uiRectCorner: UIRectCorner {
  852. var result: UIRectCorner = []
  853. if self.contains(.topLeft) { result.insert(.topLeft) }
  854. if self.contains(.topRight) { result.insert(.topRight) }
  855. if self.contains(.bottomLeft) { result.insert(.bottomLeft) }
  856. if self.contains(.bottomRight) { result.insert(.bottomRight) }
  857. return result
  858. }
  859. }
  860. #endif