Image.swift 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943
  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: [.compressionFactor: 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. /// - parameter backgroundColor: The background color for the output image
  297. ///
  298. /// - returns: An image with round corner of `self`.
  299. ///
  300. /// - Note: This method only works for CG-based image.
  301. public func image(withRoundRadius radius: CGFloat,
  302. fit size: CGSize,
  303. roundingCorners corners: RectCorner = .all,
  304. backgroundColor: Color? = nil) -> Image
  305. {
  306. guard let cgImage = cgImage else {
  307. assertionFailure("[Kingfisher] Round corner image only works for CG-based image.")
  308. return base
  309. }
  310. let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
  311. return draw(cgImage: cgImage, to: size) {
  312. #if os(macOS)
  313. if let backgroundColor = backgroundColor {
  314. let rectPath = NSBezierPath(rect: rect)
  315. backgroundColor.setFill()
  316. rectPath.fill()
  317. }
  318. let path = NSBezierPath(roundedRect: rect, byRoundingCorners: corners, radius: radius)
  319. path.windingRule = .evenOddWindingRule
  320. path.addClip()
  321. base.draw(in: rect)
  322. #else
  323. guard let context = UIGraphicsGetCurrentContext() else {
  324. assertionFailure("[Kingfisher] Failed to create CG context for image.")
  325. return
  326. }
  327. if let backgroundColor = backgroundColor {
  328. let rectPath = UIBezierPath(rect: rect)
  329. backgroundColor.setFill()
  330. rectPath.fill()
  331. }
  332. let path = UIBezierPath(roundedRect: rect,
  333. byRoundingCorners: corners.uiRectCorner,
  334. cornerRadii: CGSize(width: radius, height: radius)).cgPath
  335. context.addPath(path)
  336. context.clip()
  337. base.draw(in: rect)
  338. #endif
  339. }
  340. }
  341. #if os(iOS) || os(tvOS)
  342. func resize(to size: CGSize, for contentMode: UIViewContentMode) -> Image {
  343. switch contentMode {
  344. case .scaleAspectFit:
  345. return resize(to: size, for: .aspectFit)
  346. case .scaleAspectFill:
  347. return resize(to: size, for: .aspectFill)
  348. default:
  349. return resize(to: size)
  350. }
  351. }
  352. #endif
  353. // MARK: - Resize
  354. /// Resize `self` to an image of new size.
  355. ///
  356. /// - parameter size: The target size.
  357. ///
  358. /// - returns: An image with new size.
  359. ///
  360. /// - Note: This method only works for CG-based image.
  361. public func resize(to size: CGSize) -> Image {
  362. guard let cgImage = cgImage else {
  363. assertionFailure("[Kingfisher] Resize only works for CG-based image.")
  364. return base
  365. }
  366. let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
  367. return draw(cgImage: cgImage, to: size) {
  368. #if os(macOS)
  369. base.draw(in: rect, from: NSRect.zero, operation: .copy, fraction: 1.0)
  370. #else
  371. base.draw(in: rect)
  372. #endif
  373. }
  374. }
  375. /// Resize `self` to an image of new size, respecting the content mode.
  376. ///
  377. /// - Parameters:
  378. /// - size: The target size.
  379. /// - contentMode: Content mode of output image should be.
  380. /// - Returns: An image with new size.
  381. public func resize(to size: CGSize, for contentMode: ContentMode) -> Image {
  382. switch contentMode {
  383. case .aspectFit:
  384. let newSize = self.size.kf.constrained(size)
  385. return resize(to: newSize)
  386. case .aspectFill:
  387. let newSize = self.size.kf.filling(size)
  388. return resize(to: newSize)
  389. default:
  390. return resize(to: size)
  391. }
  392. }
  393. public func crop(to size: CGSize, anchorOn anchor: CGPoint) -> Image {
  394. guard let cgImage = cgImage else {
  395. assertionFailure("[Kingfisher] Crop only works for CG-based image.")
  396. return base
  397. }
  398. let rect = self.size.kf.constrainedRect(for: size, anchor: anchor)
  399. guard let image = cgImage.cropping(to: rect.scaled(scale)) else {
  400. assertionFailure("[Kingfisher] Cropping image failed.")
  401. return base
  402. }
  403. return Kingfisher.image(cgImage: image, scale: scale, refImage: base)
  404. }
  405. // MARK: - Blur
  406. /// Create an image with blur effect based on `self`.
  407. ///
  408. /// - parameter radius: The blur radius should be used when creating blur effect.
  409. ///
  410. /// - returns: An image with blur effect applied.
  411. ///
  412. /// - Note: This method only works for CG-based image.
  413. public func blurred(withRadius radius: CGFloat) -> Image {
  414. #if os(watchOS)
  415. return base
  416. #else
  417. guard let cgImage = cgImage else {
  418. assertionFailure("[Kingfisher] Blur only works for CG-based image.")
  419. return base
  420. }
  421. // http://www.w3.org/TR/SVG/filters.html#feGaussianBlurElement
  422. // let d = floor(s * 3*sqrt(2*pi)/4 + 0.5)
  423. // if d is odd, use three box-blurs of size 'd', centered on the output pixel.
  424. let s = Float(max(radius, 2.0))
  425. // We will do blur on a resized image (*0.5), so the blur radius could be half as well.
  426. // Fix the slow compiling time for Swift 3.
  427. // See https://github.com/onevcat/Kingfisher/issues/611
  428. let pi2 = 2 * Float.pi
  429. let sqrtPi2 = sqrt(pi2)
  430. var targetRadius = floor(s * 3.0 * sqrtPi2 / 4.0 + 0.5)
  431. if targetRadius.isEven {
  432. targetRadius += 1
  433. }
  434. let iterations: Int
  435. if radius < 0.5 {
  436. iterations = 1
  437. } else if radius < 1.5 {
  438. iterations = 2
  439. } else {
  440. iterations = 3
  441. }
  442. let w = Int(size.width)
  443. let h = Int(size.height)
  444. let rowBytes = Int(CGFloat(cgImage.bytesPerRow))
  445. func createEffectBuffer(_ context: CGContext) -> vImage_Buffer {
  446. let data = context.data
  447. let width = vImagePixelCount(context.width)
  448. let height = vImagePixelCount(context.height)
  449. let rowBytes = context.bytesPerRow
  450. return vImage_Buffer(data: data, height: height, width: width, rowBytes: rowBytes)
  451. }
  452. guard let context = beginContext(size: size, scale: scale) else {
  453. assertionFailure("[Kingfisher] Failed to create CG context for blurring image.")
  454. return base
  455. }
  456. defer { endContext() }
  457. context.draw(cgImage, in: CGRect(x: 0, y: 0, width: w, height: h))
  458. var inBuffer = createEffectBuffer(context)
  459. guard let outContext = beginContext(size: size, scale: scale) else {
  460. assertionFailure("[Kingfisher] Failed to create CG context for blurring image.")
  461. return base
  462. }
  463. defer { endContext() }
  464. var outBuffer = createEffectBuffer(outContext)
  465. for _ in 0 ..< iterations {
  466. vImageBoxConvolve_ARGB8888(&inBuffer, &outBuffer, nil, 0, 0, UInt32(targetRadius), UInt32(targetRadius), nil, vImage_Flags(kvImageEdgeExtend))
  467. (inBuffer, outBuffer) = (outBuffer, inBuffer)
  468. }
  469. #if os(macOS)
  470. let result = outContext.makeImage().flatMap { fixedForRetinaPixel(cgImage: $0, to: size) }
  471. #else
  472. let result = outContext.makeImage().flatMap { Image(cgImage: $0, scale: base.scale, orientation: base.imageOrientation) }
  473. #endif
  474. guard let blurredImage = result else {
  475. assertionFailure("[Kingfisher] Can not make an blurred image within this context.")
  476. return base
  477. }
  478. return blurredImage
  479. #endif
  480. }
  481. // MARK: - Overlay
  482. /// Create an image from `self` with a color overlay layer.
  483. ///
  484. /// - parameter color: The color should be use to overlay.
  485. /// - parameter fraction: Fraction of input color. From 0.0 to 1.0. 0.0 means solid color, 1.0 means transparent overlay.
  486. ///
  487. /// - returns: An image with a color overlay applied.
  488. ///
  489. /// - Note: This method only works for CG-based image.
  490. public func overlaying(with color: Color, fraction: CGFloat) -> Image {
  491. guard let cgImage = cgImage else {
  492. assertionFailure("[Kingfisher] Overlaying only works for CG-based image.")
  493. return base
  494. }
  495. let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
  496. return draw(cgImage: cgImage, to: rect.size) {
  497. #if os(macOS)
  498. base.draw(in: rect)
  499. if fraction > 0 {
  500. color.withAlphaComponent(1 - fraction).set()
  501. rect.fill(using: .sourceAtop)
  502. }
  503. #else
  504. color.set()
  505. UIRectFill(rect)
  506. base.draw(in: rect, blendMode: .destinationIn, alpha: 1.0)
  507. if fraction > 0 {
  508. base.draw(in: rect, blendMode: .sourceAtop, alpha: fraction)
  509. }
  510. #endif
  511. }
  512. }
  513. // MARK: - Tint
  514. /// Create an image from `self` with a color tint.
  515. ///
  516. /// - parameter color: The color should be used to tint `self`
  517. ///
  518. /// - returns: An image with a color tint applied.
  519. public func tinted(with color: Color) -> Image {
  520. #if os(watchOS)
  521. return base
  522. #else
  523. return apply(.tint(color))
  524. #endif
  525. }
  526. // MARK: - Color Control
  527. /// Create an image from `self` with color control.
  528. ///
  529. /// - parameter brightness: Brightness changing to image.
  530. /// - parameter contrast: Contrast changing to image.
  531. /// - parameter saturation: Saturation changing to image.
  532. /// - parameter inputEV: InputEV changing to image.
  533. ///
  534. /// - returns: An image with color control applied.
  535. public func adjusted(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) -> Image {
  536. #if os(watchOS)
  537. return base
  538. #else
  539. return apply(.colorControl((brightness, contrast, saturation, inputEV)))
  540. #endif
  541. }
  542. }
  543. // MARK: - Decode
  544. extension Kingfisher where Base: Image {
  545. var decoded: Image {
  546. return decoded(scale: scale)
  547. }
  548. func decoded(scale: CGFloat) -> Image {
  549. // prevent animated image (GIF) lose it's images
  550. #if os(iOS)
  551. if imageSource != nil { return base }
  552. #else
  553. if images != nil { return base }
  554. #endif
  555. guard let imageRef = self.cgImage else {
  556. assertionFailure("[Kingfisher] Decoding only works for CG-based image.")
  557. return base
  558. }
  559. // Draw CGImage in a plain context with scale of 1.0.
  560. guard let context = beginContext(size: CGSize(width: imageRef.width, height: imageRef.height), scale: 1.0) else {
  561. assertionFailure("[Kingfisher] Decoding fails to create a valid context.")
  562. return base
  563. }
  564. defer { endContext() }
  565. let rect = CGRect(x: 0, y: 0, width: CGFloat(imageRef.width), height: CGFloat(imageRef.height))
  566. context.draw(imageRef, in: rect)
  567. let decompressedImageRef = context.makeImage()
  568. return Kingfisher<Image>.image(cgImage: decompressedImageRef!, scale: scale, refImage: base)
  569. }
  570. }
  571. /// Reference the source image reference
  572. class ImageSource {
  573. var imageRef: CGImageSource?
  574. init(ref: CGImageSource) {
  575. self.imageRef = ref
  576. }
  577. }
  578. // MARK: - Image format
  579. private struct ImageHeaderData {
  580. static var PNG: [UInt8] = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]
  581. static var JPEG_SOI: [UInt8] = [0xFF, 0xD8]
  582. static var JPEG_IF: [UInt8] = [0xFF]
  583. static var GIF: [UInt8] = [0x47, 0x49, 0x46]
  584. }
  585. enum ImageFormat {
  586. case unknown, PNG, JPEG, GIF
  587. }
  588. // MARK: - Misc Helpers
  589. public struct DataProxy {
  590. fileprivate let base: Data
  591. init(proxy: Data) {
  592. base = proxy
  593. }
  594. }
  595. extension Data: KingfisherCompatible {
  596. public typealias CompatibleType = DataProxy
  597. public var kf: DataProxy {
  598. return DataProxy(proxy: self)
  599. }
  600. }
  601. extension DataProxy {
  602. var imageFormat: ImageFormat {
  603. var buffer = [UInt8](repeating: 0, count: 8)
  604. (base as NSData).getBytes(&buffer, length: 8)
  605. if buffer == ImageHeaderData.PNG {
  606. return .PNG
  607. } else if buffer[0] == ImageHeaderData.JPEG_SOI[0] &&
  608. buffer[1] == ImageHeaderData.JPEG_SOI[1] &&
  609. buffer[2] == ImageHeaderData.JPEG_IF[0]
  610. {
  611. return .JPEG
  612. } else if buffer[0] == ImageHeaderData.GIF[0] &&
  613. buffer[1] == ImageHeaderData.GIF[1] &&
  614. buffer[2] == ImageHeaderData.GIF[2]
  615. {
  616. return .GIF
  617. }
  618. return .unknown
  619. }
  620. }
  621. public struct CGSizeProxy {
  622. fileprivate let base: CGSize
  623. init(proxy: CGSize) {
  624. base = proxy
  625. }
  626. }
  627. extension CGSize: KingfisherCompatible {
  628. public typealias CompatibleType = CGSizeProxy
  629. public var kf: CGSizeProxy {
  630. return CGSizeProxy(proxy: self)
  631. }
  632. }
  633. extension CGSizeProxy {
  634. func constrained(_ size: CGSize) -> CGSize {
  635. let aspectWidth = round(aspectRatio * size.height)
  636. let aspectHeight = round(size.width / aspectRatio)
  637. return aspectWidth > size.width ? CGSize(width: size.width, height: aspectHeight) : CGSize(width: aspectWidth, height: size.height)
  638. }
  639. func filling(_ size: CGSize) -> CGSize {
  640. let aspectWidth = round(aspectRatio * size.height)
  641. let aspectHeight = round(size.width / aspectRatio)
  642. return aspectWidth < size.width ? CGSize(width: size.width, height: aspectHeight) : CGSize(width: aspectWidth, height: size.height)
  643. }
  644. private var aspectRatio: CGFloat {
  645. return base.height == 0.0 ? 1.0 : base.width / base.height
  646. }
  647. func constrainedRect(for size: CGSize, anchor: CGPoint) -> CGRect {
  648. let unifiedAnchor = CGPoint(x: anchor.x.clamped(to: 0.0...1.0),
  649. y: anchor.y.clamped(to: 0.0...1.0))
  650. let x = unifiedAnchor.x * base.width - unifiedAnchor.x * size.width
  651. let y = unifiedAnchor.y * base.height - unifiedAnchor.y * size.height
  652. let r = CGRect(x: x, y: y, width: size.width, height: size.height)
  653. let ori = CGRect(origin: CGPoint.zero, size: base)
  654. return ori.intersection(r)
  655. }
  656. }
  657. extension CGRect {
  658. func scaled(_ scale: CGFloat) -> CGRect {
  659. return CGRect(x: origin.x * scale, y: origin.y * scale,
  660. width: size.width * scale, height: size.height * scale)
  661. }
  662. }
  663. extension Comparable {
  664. func clamped(to limits: ClosedRange<Self>) -> Self {
  665. return min(max(self, limits.lowerBound), limits.upperBound)
  666. }
  667. }
  668. extension Kingfisher where Base: Image {
  669. func beginContext(size: CGSize, scale: CGFloat) -> CGContext? {
  670. #if os(macOS)
  671. guard let rep = NSBitmapImageRep(
  672. bitmapDataPlanes: nil,
  673. pixelsWide: Int(size.width),
  674. pixelsHigh: Int(size.height),
  675. bitsPerSample: cgImage?.bitsPerComponent ?? 8,
  676. samplesPerPixel: 4,
  677. hasAlpha: true,
  678. isPlanar: false,
  679. colorSpaceName: .calibratedRGB,
  680. bytesPerRow: 0,
  681. bitsPerPixel: 0) else
  682. {
  683. assertionFailure("[Kingfisher] Image representation cannot be created.")
  684. return nil
  685. }
  686. rep.size = size
  687. NSGraphicsContext.saveGraphicsState()
  688. guard let context = NSGraphicsContext(bitmapImageRep: rep) else {
  689. assertionFailure("[Kingfisher] Image contenxt cannot be created.")
  690. return nil
  691. }
  692. NSGraphicsContext.current = context
  693. return context.cgContext
  694. #else
  695. UIGraphicsBeginImageContextWithOptions(size, false, scale)
  696. let context = UIGraphicsGetCurrentContext()
  697. context?.scaleBy(x: 1.0, y: -1.0)
  698. context?.translateBy(x: 0, y: -size.height)
  699. return context
  700. #endif
  701. }
  702. func endContext() {
  703. #if os(macOS)
  704. NSGraphicsContext.restoreGraphicsState()
  705. #else
  706. UIGraphicsEndImageContext()
  707. #endif
  708. }
  709. func draw(cgImage: CGImage?, to size: CGSize, draw: ()->()) -> Image {
  710. #if os(macOS)
  711. guard let rep = NSBitmapImageRep(
  712. bitmapDataPlanes: nil,
  713. pixelsWide: Int(size.width),
  714. pixelsHigh: Int(size.height),
  715. bitsPerSample: cgImage?.bitsPerComponent ?? 8,
  716. samplesPerPixel: 4,
  717. hasAlpha: true,
  718. isPlanar: false,
  719. colorSpaceName: .calibratedRGB,
  720. bytesPerRow: 0,
  721. bitsPerPixel: 0) else
  722. {
  723. assertionFailure("[Kingfisher] Image representation cannot be created.")
  724. return base
  725. }
  726. rep.size = size
  727. NSGraphicsContext.saveGraphicsState()
  728. let context = NSGraphicsContext(bitmapImageRep: rep)
  729. NSGraphicsContext.current = context
  730. draw()
  731. NSGraphicsContext.restoreGraphicsState()
  732. let outputImage = Image(size: size)
  733. outputImage.addRepresentation(rep)
  734. return outputImage
  735. #else
  736. UIGraphicsBeginImageContextWithOptions(size, false, scale)
  737. defer { UIGraphicsEndImageContext() }
  738. draw()
  739. return UIGraphicsGetImageFromCurrentImageContext() ?? base
  740. #endif
  741. }
  742. #if os(macOS)
  743. func fixedForRetinaPixel(cgImage: CGImage, to size: CGSize) -> Image {
  744. let image = Image(cgImage: cgImage, size: base.size)
  745. let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
  746. return draw(cgImage: cgImage, to: self.size) {
  747. image.draw(in: rect, from: NSRect.zero, operation: .copy, fraction: 1.0)
  748. }
  749. }
  750. #endif
  751. }
  752. extension Float {
  753. var isEven: Bool {
  754. return truncatingRemainder(dividingBy: 2.0) == 0
  755. }
  756. }
  757. #if os(macOS)
  758. extension NSBezierPath {
  759. convenience init(roundedRect rect: NSRect, topLeftRadius: CGFloat, topRightRadius: CGFloat,
  760. bottomLeftRadius: CGFloat, bottomRightRadius: CGFloat)
  761. {
  762. self.init()
  763. let maxCorner = min(rect.width, rect.height) / 2
  764. let radiusTopLeft = min(maxCorner, max(0, topLeftRadius))
  765. let radiustopRight = min(maxCorner, max(0, topRightRadius))
  766. let radiusbottomLeft = min(maxCorner, max(0, bottomLeftRadius))
  767. let radiusbottomRight = min(maxCorner, max(0, bottomRightRadius))
  768. guard !NSIsEmptyRect(rect) else {
  769. return
  770. }
  771. let topLeft = NSMakePoint(NSMinX(rect), NSMaxY(rect));
  772. let topRight = NSMakePoint(NSMaxX(rect), NSMaxY(rect));
  773. let bottomRight = NSMakePoint(NSMaxX(rect), NSMinY(rect));
  774. move(to: NSMakePoint(NSMidX(rect), NSMaxY(rect)))
  775. appendArc(from: topLeft, to: rect.origin, radius: radiusTopLeft)
  776. appendArc(from: rect.origin, to: bottomRight, radius: radiusbottomLeft)
  777. appendArc(from: bottomRight, to: topRight, radius: radiusbottomRight)
  778. appendArc(from: topRight, to: topLeft, radius: radiustopRight)
  779. close()
  780. }
  781. convenience init(roundedRect rect: NSRect, byRoundingCorners corners: RectCorner, radius: CGFloat) {
  782. let radiusTopLeft = corners.contains(.topLeft) ? radius : 0
  783. let radiusTopRight = corners.contains(.topRight) ? radius : 0
  784. let radiusBottomLeft = corners.contains(.bottomLeft) ? radius : 0
  785. let radiusBottomRight = corners.contains(.bottomRight) ? radius : 0
  786. self.init(roundedRect: rect, topLeftRadius: radiusTopLeft, topRightRadius: radiusTopRight,
  787. bottomLeftRadius: radiusBottomLeft, bottomRightRadius: radiusBottomRight)
  788. }
  789. }
  790. #else
  791. extension RectCorner {
  792. var uiRectCorner: UIRectCorner {
  793. var result: UIRectCorner = []
  794. if self.contains(.topLeft) { result.insert(.topLeft) }
  795. if self.contains(.topRight) { result.insert(.topRight) }
  796. if self.contains(.bottomLeft) { result.insert(.bottomLeft) }
  797. if self.contains(.bottomRight) { result.insert(.bottomRight) }
  798. return result
  799. }
  800. }
  801. #endif