Image.swift 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044
  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) 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) 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. guard let context = beginContext(size: CGSize(width: imageRef.width, height: imageRef.height)) else {
  548. assertionFailure("[Kingfisher] Decoding fails to create a valid context.")
  549. return base
  550. }
  551. defer { endContext() }
  552. let rect = CGRect(x: 0, y: 0, width: imageRef.width, height: imageRef.height)
  553. context.draw(imageRef, in: rect)
  554. let decompressedImageRef = context.makeImage()
  555. return Kingfisher<Image>.image(cgImage: decompressedImageRef!, scale: scale, refImage: base)
  556. }
  557. }
  558. /// Reference the source image reference
  559. class ImageSource {
  560. var imageRef: CGImageSource?
  561. init(ref: CGImageSource) {
  562. self.imageRef = ref
  563. }
  564. }
  565. // MARK: - Image format
  566. private struct ImageHeaderData {
  567. static var PNG: [UInt8] = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]
  568. static var JPEG_SOI: [UInt8] = [0xFF, 0xD8]
  569. static var JPEG_IF: [UInt8] = [0xFF]
  570. static var GIF: [UInt8] = [0x47, 0x49, 0x46]
  571. }
  572. enum ImageFormat {
  573. case unknown, PNG, JPEG, GIF
  574. }
  575. // MARK: - Misc Helpers
  576. public struct DataProxy {
  577. fileprivate let base: Data
  578. init(proxy: Data) {
  579. base = proxy
  580. }
  581. }
  582. extension Data: KingfisherCompatible {
  583. public typealias CompatibleType = DataProxy
  584. public var kf: DataProxy {
  585. return DataProxy(proxy: self)
  586. }
  587. }
  588. extension DataProxy {
  589. var imageFormat: ImageFormat {
  590. var buffer = [UInt8](repeating: 0, count: 8)
  591. (base as NSData).getBytes(&buffer, length: 8)
  592. if buffer == ImageHeaderData.PNG {
  593. return .PNG
  594. } else if buffer[0] == ImageHeaderData.JPEG_SOI[0] &&
  595. buffer[1] == ImageHeaderData.JPEG_SOI[1] &&
  596. buffer[2] == ImageHeaderData.JPEG_IF[0]
  597. {
  598. return .JPEG
  599. } else if buffer[0] == ImageHeaderData.GIF[0] &&
  600. buffer[1] == ImageHeaderData.GIF[1] &&
  601. buffer[2] == ImageHeaderData.GIF[2]
  602. {
  603. return .GIF
  604. }
  605. return .unknown
  606. }
  607. }
  608. public struct CGSizeProxy {
  609. fileprivate let base: CGSize
  610. init(proxy: CGSize) {
  611. base = proxy
  612. }
  613. }
  614. extension CGSize: KingfisherCompatible {
  615. public typealias CompatibleType = CGSizeProxy
  616. public var kf: CGSizeProxy {
  617. return CGSizeProxy(proxy: self)
  618. }
  619. }
  620. extension CGSizeProxy {
  621. func constrained(_ size: CGSize) -> CGSize {
  622. let aspectWidth = round(aspectRatio * size.height)
  623. let aspectHeight = round(size.width / aspectRatio)
  624. return aspectWidth > size.width ? CGSize(width: size.width, height: aspectHeight) : CGSize(width: aspectWidth, height: size.height)
  625. }
  626. func filling(_ size: CGSize) -> CGSize {
  627. let aspectWidth = round(aspectRatio * size.height)
  628. let aspectHeight = round(size.width / aspectRatio)
  629. return aspectWidth < size.width ? CGSize(width: size.width, height: aspectHeight) : CGSize(width: aspectWidth, height: size.height)
  630. }
  631. private var aspectRatio: CGFloat {
  632. return base.height == 0.0 ? 1.0 : base.width / base.height
  633. }
  634. func constrainedRect(for size: CGSize, anchor: CGPoint) -> CGRect {
  635. let unifiedAnchor = CGPoint(x: anchor.x.clamped(to: 0.0...1.0),
  636. y: anchor.y.clamped(to: 0.0...1.0))
  637. let x = unifiedAnchor.x * base.width - unifiedAnchor.x * size.width
  638. let y = unifiedAnchor.y * base.height - unifiedAnchor.y * size.height
  639. let r = CGRect(x: x, y: y, width: size.width, height: size.height)
  640. let ori = CGRect(origin: CGPoint.zero, size: base)
  641. return ori.intersection(r)
  642. }
  643. }
  644. extension CGRect {
  645. func scaled(_ scale: CGFloat) -> CGRect {
  646. return CGRect(x: origin.x * scale, y: origin.y * scale,
  647. width: size.width * scale, height: size.height * scale)
  648. }
  649. }
  650. extension Comparable {
  651. func clamped(to limits: ClosedRange<Self>) -> Self {
  652. return min(max(self, limits.lowerBound), limits.upperBound)
  653. }
  654. }
  655. extension Kingfisher where Base: Image {
  656. func beginContext(size: CGSize) -> CGContext? {
  657. #if os(macOS)
  658. guard let rep = NSBitmapImageRep(
  659. bitmapDataPlanes: nil,
  660. pixelsWide: Int(size.width),
  661. pixelsHigh: Int(size.height),
  662. bitsPerSample: cgImage?.bitsPerComponent ?? 8,
  663. samplesPerPixel: 4,
  664. hasAlpha: true,
  665. isPlanar: false,
  666. colorSpaceName: NSCalibratedRGBColorSpace,
  667. bytesPerRow: 0,
  668. bitsPerPixel: 0) else
  669. {
  670. assertionFailure("[Kingfisher] Image representation cannot be created.")
  671. return nil
  672. }
  673. rep.size = size
  674. NSGraphicsContext.saveGraphicsState()
  675. guard let context = NSGraphicsContext(bitmapImageRep: rep) else {
  676. assertionFailure("[Kingfisher] Image contenxt cannot be created.")
  677. return nil
  678. }
  679. NSGraphicsContext.setCurrent(context)
  680. return context.cgContext
  681. #else
  682. UIGraphicsBeginImageContextWithOptions(size, false, scale)
  683. let context = UIGraphicsGetCurrentContext()
  684. context?.scaleBy(x: 1.0, y: -1.0)
  685. context?.translateBy(x: 0, y: -size.height)
  686. return context
  687. #endif
  688. }
  689. func endContext() {
  690. #if os(macOS)
  691. NSGraphicsContext.restoreGraphicsState()
  692. #else
  693. UIGraphicsEndImageContext()
  694. #endif
  695. }
  696. func draw(cgImage: CGImage?, to size: CGSize, draw: ()->()) -> Image {
  697. #if os(macOS)
  698. guard let rep = NSBitmapImageRep(
  699. bitmapDataPlanes: nil,
  700. pixelsWide: Int(size.width),
  701. pixelsHigh: Int(size.height),
  702. bitsPerSample: cgImage?.bitsPerComponent ?? 8,
  703. samplesPerPixel: 4,
  704. hasAlpha: true,
  705. isPlanar: false,
  706. colorSpaceName: NSCalibratedRGBColorSpace,
  707. bytesPerRow: 0,
  708. bitsPerPixel: 0) else
  709. {
  710. assertionFailure("[Kingfisher] Image representation cannot be created.")
  711. return base
  712. }
  713. rep.size = size
  714. NSGraphicsContext.saveGraphicsState()
  715. let context = NSGraphicsContext(bitmapImageRep: rep)
  716. NSGraphicsContext.setCurrent(context)
  717. draw()
  718. NSGraphicsContext.restoreGraphicsState()
  719. let outputImage = Image(size: size)
  720. outputImage.addRepresentation(rep)
  721. return outputImage
  722. #else
  723. UIGraphicsBeginImageContextWithOptions(size, false, scale)
  724. defer { UIGraphicsEndImageContext() }
  725. draw()
  726. return UIGraphicsGetImageFromCurrentImageContext() ?? base
  727. #endif
  728. }
  729. #if os(macOS)
  730. func fixedForRetinaPixel(cgImage: CGImage, to size: CGSize) -> Image {
  731. let image = Image(cgImage: cgImage, size: base.size)
  732. let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
  733. return draw(cgImage: cgImage, to: self.size) {
  734. image.draw(in: rect, from: NSRect.zero, operation: .copy, fraction: 1.0)
  735. }
  736. }
  737. #endif
  738. }
  739. extension Float {
  740. var isEven: Bool {
  741. return truncatingRemainder(dividingBy: 2.0) == 0
  742. }
  743. }
  744. #if os(macOS)
  745. extension NSBezierPath {
  746. convenience init(roundedRect rect: NSRect, topLeftRadius: CGFloat, topRightRadius: CGFloat,
  747. bottomLeftRadius: CGFloat, bottomRightRadius: CGFloat)
  748. {
  749. self.init()
  750. let maxCorner = min(rect.width, rect.height) / 2
  751. let radiusTopLeft = min(maxCorner, max(0, topLeftRadius))
  752. let radiustopRight = min(maxCorner, max(0, topRightRadius))
  753. let radiusbottomLeft = min(maxCorner, max(0, bottomLeftRadius))
  754. let radiusbottomRight = min(maxCorner, max(0, bottomRightRadius))
  755. guard !NSIsEmptyRect(rect) else {
  756. return
  757. }
  758. let topLeft = NSMakePoint(NSMinX(rect), NSMaxY(rect));
  759. let topRight = NSMakePoint(NSMaxX(rect), NSMaxY(rect));
  760. let bottomRight = NSMakePoint(NSMaxX(rect), NSMinY(rect));
  761. move(to: NSMakePoint(NSMidX(rect), NSMaxY(rect)))
  762. appendArc(from: topLeft, to: rect.origin, radius: radiusTopLeft)
  763. appendArc(from: rect.origin, to: bottomRight, radius: radiusbottomLeft)
  764. appendArc(from: bottomRight, to: topRight, radius: radiusbottomRight)
  765. appendArc(from: topRight, to: topLeft, radius: radiustopRight)
  766. close()
  767. }
  768. convenience init(roundedRect rect: NSRect, byRoundingCorners corners: RectCorner, radius: CGFloat) {
  769. let radiusTopLeft = corners.contains(.topLeft) ? radius : 0
  770. let radiusTopRight = corners.contains(.topRight) ? radius : 0
  771. let radiusBottomLeft = corners.contains(.bottomLeft) ? radius : 0
  772. let radiusBottomRight = corners.contains(.bottomRight) ? radius : 0
  773. self.init(roundedRect: rect, topLeftRadius: radiusTopLeft, topRightRadius: radiusTopRight,
  774. bottomLeftRadius: radiusBottomLeft, bottomRightRadius: radiusBottomRight)
  775. }
  776. }
  777. #else
  778. extension RectCorner {
  779. var uiRectCorner: UIRectCorner {
  780. var result: UIRectCorner = []
  781. if self.contains(.topLeft) { result.insert(.topLeft) }
  782. if self.contains(.topRight) { result.insert(.topRight) }
  783. if self.contains(.bottomLeft) { result.insert(.bottomLeft) }
  784. if self.contains(.bottomRight) { result.insert(.bottomRight) }
  785. return result
  786. }
  787. }
  788. #endif
  789. // MARK: - Deprecated. Only for back compatibility.
  790. extension Image {
  791. /**
  792. Normalize the image. This method does nothing in OS X.
  793. - returns: The image itself.
  794. */
  795. @available(*, deprecated,
  796. message: "Extensions directly on Image are deprecated. Use `kf.normalized` instead.",
  797. renamed: "kf.normalized")
  798. public func kf_normalized() -> Image {
  799. return kf.normalized
  800. }
  801. // MARK: - Round Corner
  802. /// Create a round corner image based on `self`.
  803. ///
  804. /// - parameter radius: The round corner radius of creating image.
  805. /// - parameter size: The target size of creating image.
  806. /// - parameter scale: The image scale of creating image.
  807. ///
  808. /// - returns: An image with round corner of `self`.
  809. ///
  810. /// - Note: This method only works for CG-based image.
  811. @available(*, deprecated,
  812. message: "Extensions directly on Image are deprecated. Use `kf.image(withRoundRadius:fit:scale:)` instead.",
  813. renamed: "kf.image")
  814. public func kf_image(withRoundRadius radius: CGFloat, fit size: CGSize, scale: CGFloat) -> Image {
  815. return kf.image(withRoundRadius: radius, fit: size)
  816. }
  817. // MARK: - Resize
  818. /// Resize `self` to an image of new size.
  819. ///
  820. /// - parameter size: The target size.
  821. ///
  822. /// - returns: An image with new size.
  823. ///
  824. /// - Note: This method only works for CG-based image.
  825. @available(*, deprecated,
  826. message: "Extensions directly on Image are deprecated. Use `kf.resize(to:)` instead.",
  827. renamed: "kf.resize")
  828. public func kf_resize(to size: CGSize) -> Image {
  829. return kf.resize(to: size)
  830. }
  831. // MARK: - Blur
  832. /// Create an image with blur effect based on `self`.
  833. ///
  834. /// - parameter radius: The blur radius should be used when creating blue.
  835. ///
  836. /// - returns: An image with blur effect applied.
  837. ///
  838. /// - Note: This method only works for CG-based image.
  839. @available(*, deprecated,
  840. message: "Extensions directly on Image are deprecated. Use `kf.blurred(withRadius:)` instead.",
  841. renamed: "kf.blurred")
  842. public func kf_blurred(withRadius radius: CGFloat) -> Image {
  843. return kf.blurred(withRadius: radius)
  844. }
  845. // MARK: - Overlay
  846. /// Create an image from `self` with a color overlay layer.
  847. ///
  848. /// - parameter color: The color should be use to overlay.
  849. /// - parameter fraction: Fraction of input color. From 0.0 to 1.0. 0.0 means solid color, 1.0 means transparent overlay.
  850. ///
  851. /// - returns: An image with a color overlay applied.
  852. ///
  853. /// - Note: This method only works for CG-based image.
  854. @available(*, deprecated,
  855. message: "Extensions directly on Image are deprecated. Use `kf.overlaying(with:fraction:)` instead.",
  856. renamed: "kf.overlaying")
  857. public func kf_overlaying(with color: Color, fraction: CGFloat) -> Image {
  858. return kf.overlaying(with: color, fraction: fraction)
  859. }
  860. // MARK: - Tint
  861. /// Create an image from `self` with a color tint.
  862. ///
  863. /// - parameter color: The color should be used to tint `self`
  864. ///
  865. /// - returns: An image with a color tint applied.
  866. @available(*, deprecated,
  867. message: "Extensions directly on Image are deprecated. Use `kf.tinted(with:)` instead.",
  868. renamed: "kf.tinted")
  869. public func kf_tinted(with color: Color) -> Image {
  870. return kf.tinted(with: color)
  871. }
  872. // MARK: - Color Control
  873. /// Create an image from `self` with color control.
  874. ///
  875. /// - parameter brightness: Brightness changing to image.
  876. /// - parameter contrast: Contrast changing to image.
  877. /// - parameter saturation: Saturation changing to image.
  878. /// - parameter inputEV: InputEV changing to image.
  879. ///
  880. /// - returns: An image with color control applied.
  881. @available(*, deprecated,
  882. message: "Extensions directly on Image are deprecated. Use `kf.adjusted` instead.",
  883. renamed: "kf.adjusted")
  884. public func kf_adjusted(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) -> Image {
  885. return kf.adjusted(brightness: brightness, contrast: contrast, saturation: saturation, inputEV: inputEV)
  886. }
  887. }
  888. extension Kingfisher where Base: Image {
  889. @available(*, deprecated,
  890. message: "`scale` is not used. Use the version without scale instead. (Remove the `scale` argument)")
  891. public func image(withRoundRadius radius: CGFloat, fit size: CGSize, scale: CGFloat) -> Image {
  892. return image(withRoundRadius: radius, fit: size)
  893. }
  894. }