Image.swift 36 KB

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