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