Image.swift 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827
  1. //
  2. // Image.swift
  3. // Kingfisher
  4. //
  5. // Created by Wei Wang on 16/1/6.
  6. //
  7. // Copyright (c) 2016 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. public typealias Image = NSImage
  29. public typealias Color = NSColor
  30. private var imagesKey: Void?
  31. private var durationKey: Void?
  32. #else
  33. import UIKit
  34. import MobileCoreServices
  35. public typealias Image = UIImage
  36. public typealias Color = UIColor
  37. private var imageSourceKey: Void?
  38. private var animatedImageDataKey: Void?
  39. #endif
  40. import ImageIO
  41. import CoreGraphics
  42. #if !os(watchOS)
  43. import Accelerate
  44. import CoreImage
  45. #endif
  46. // MARK: - Image Properties
  47. extension Image {
  48. #if os(macOS)
  49. var cgImage: CGImage? {
  50. return cgImage(forProposedRect: nil, context: nil, hints: nil)
  51. }
  52. var kf_scale: CGFloat {
  53. return 1.0
  54. }
  55. fileprivate(set) var kf_images: [Image]? {
  56. get {
  57. return objc_getAssociatedObject(self, &imagesKey) as? [Image]
  58. }
  59. set {
  60. objc_setAssociatedObject(self, &imagesKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
  61. }
  62. }
  63. fileprivate(set) var kf_duration: TimeInterval {
  64. get {
  65. return objc_getAssociatedObject(self, &durationKey) as? TimeInterval ?? 0.0
  66. }
  67. set {
  68. objc_setAssociatedObject(self, &durationKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
  69. }
  70. }
  71. var kf_size: CGSize {
  72. return representations.reduce(CGSize.zero, { size, rep in
  73. return CGSize(width: max(size.width, CGFloat(rep.pixelsWide)), height: max(size.height, CGFloat(rep.pixelsHigh)))
  74. })
  75. }
  76. #else
  77. var kf_scale: CGFloat {
  78. return scale
  79. }
  80. var kf_images: [Image]? {
  81. return images
  82. }
  83. var kf_duration: TimeInterval {
  84. return duration
  85. }
  86. fileprivate(set) var kf_imageSource: ImageSource? {
  87. get {
  88. return objc_getAssociatedObject(self, &imageSourceKey) as? ImageSource
  89. }
  90. set {
  91. objc_setAssociatedObject(self, &imageSourceKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
  92. }
  93. }
  94. fileprivate(set) var kf_animatedImageData: Data? {
  95. get {
  96. return objc_getAssociatedObject(self, &animatedImageDataKey) as? Data
  97. }
  98. set {
  99. objc_setAssociatedObject(self, &animatedImageDataKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
  100. }
  101. }
  102. var kf_size: CGSize {
  103. return size
  104. }
  105. #endif
  106. }
  107. // MARK: - Image Conversion
  108. extension Image {
  109. #if os(macOS)
  110. static func kf_image(cgImage: CGImage, scale: CGFloat, refImage: Image?) -> Image {
  111. return Image(cgImage: cgImage, size: CGSize.zero)
  112. }
  113. /**
  114. Normalize the image. This method does nothing in OS X.
  115. - returns: The image itself.
  116. */
  117. public func kf_normalized() -> Image {
  118. return self
  119. }
  120. static func kf_animated(with images: [Image], forDuration forDurationduration: TimeInterval) -> Image? {
  121. return nil
  122. }
  123. #else
  124. static func kf_image(cgImage: CGImage, scale: CGFloat, refImage: Image?) -> Image {
  125. if let refImage = refImage {
  126. return Image(cgImage: cgImage, scale: scale, orientation: refImage.imageOrientation)
  127. } else {
  128. return Image(cgImage: cgImage, scale: scale, orientation: .up)
  129. }
  130. }
  131. /**
  132. Normalize the image. This method will try to redraw an image with orientation and scale considered.
  133. - returns: The normalized image with orientation set to up and correct scale.
  134. */
  135. public func kf_normalized() -> Image {
  136. // prevent animated image (GIF) lose it's images
  137. guard images == nil else { return self }
  138. // No need to do anything if already up
  139. guard imageOrientation != .up else { return self }
  140. return draw(cgImage: nil, to: size) {
  141. draw(in: CGRect(origin: CGPoint.zero, size: size))
  142. }
  143. }
  144. static func kf_animated(with images: [Image], forDuration duration: TimeInterval) -> Image? {
  145. return .animatedImage(with: images, duration: duration)
  146. }
  147. #endif
  148. }
  149. // MARK: - Image Representation
  150. extension Image {
  151. // MARK: - PNG
  152. func pngRepresentation() -> Data? {
  153. #if os(macOS)
  154. guard let cgimage = cgImage else {
  155. return nil
  156. }
  157. let rep = NSBitmapImageRep(cgImage: cgimage)
  158. return rep.representation(using: .PNG, properties: [:])
  159. #else
  160. return UIImagePNGRepresentation(self)
  161. #endif
  162. }
  163. // MARK: - JPEG
  164. func jpegRepresentation(compressionQuality: CGFloat) -> Data? {
  165. #if os(macOS)
  166. guard let cgImage = cgImage else {
  167. return nil
  168. }
  169. let rep = NSBitmapImageRep(cgImage: cgImage)
  170. return rep.representation(using:.JPEG, properties: [NSImageCompressionFactor: compressionQuality])
  171. #else
  172. return UIImageJPEGRepresentation(self, compressionQuality)
  173. #endif
  174. }
  175. // MARK: - GIF
  176. func gifRepresentation() -> Data? {
  177. #if os(macOS)
  178. return gifRepresentation(duration: 0.0, repeatCount: 0)
  179. #else
  180. return kf_animatedImageData
  181. #endif
  182. }
  183. #if os(macOS)
  184. func gifRepresentation(duration: TimeInterval, repeatCount: Int) -> Data? {
  185. guard let images = kf_images else {
  186. return nil
  187. }
  188. let frameCount = images.count
  189. let gifDuration = duration <= 0.0 ? kf_duration / Double(frameCount) : duration / Double(frameCount)
  190. let frameProperties = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFDelayTime as String: gifDuration]]
  191. let imageProperties = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFLoopCount as String: repeatCount]]
  192. let data = NSMutableData()
  193. guard let destination = CGImageDestinationCreateWithData(data, kUTTypeGIF, frameCount, nil) else {
  194. return nil
  195. }
  196. CGImageDestinationSetProperties(destination, imageProperties as CFDictionary)
  197. for image in images {
  198. CGImageDestinationAddImage(destination, image.cgImage!, frameProperties as CFDictionary)
  199. }
  200. return CGImageDestinationFinalize(destination) ? data.copy() as? Data : nil
  201. }
  202. #endif
  203. }
  204. // MARK: - Create images from data
  205. extension Image {
  206. static func kf_animated(with data: Data, scale: CGFloat = 1.0, duration: TimeInterval = 0.0, preloadAll: Bool) -> Image? {
  207. func decode(from imageSource: CGImageSource, for options: NSDictionary) -> ([Image], TimeInterval)? {
  208. //Calculates frame duration for a gif frame out of the kCGImagePropertyGIFDictionary dictionary
  209. func frameDuration(from gifInfo: NSDictionary) -> Double {
  210. let gifDefaultFrameDuration = 0.100
  211. let unclampedDelayTime = gifInfo[kCGImagePropertyGIFUnclampedDelayTime as String] as? NSNumber
  212. let delayTime = gifInfo[kCGImagePropertyGIFDelayTime as String] as? NSNumber
  213. let duration = unclampedDelayTime ?? delayTime
  214. guard let frameDuration = duration else { return gifDefaultFrameDuration }
  215. return frameDuration.doubleValue > 0.011 ? frameDuration.doubleValue : gifDefaultFrameDuration
  216. }
  217. let frameCount = CGImageSourceGetCount(imageSource)
  218. var images = [Image]()
  219. var gifDuration = 0.0
  220. for i in 0 ..< frameCount {
  221. guard let imageRef = CGImageSourceCreateImageAtIndex(imageSource, i, options) else {
  222. return nil
  223. }
  224. if frameCount == 1 {
  225. // Single frame
  226. gifDuration = Double.infinity
  227. } else {
  228. // Animated GIF
  229. guard let properties = CGImageSourceCopyPropertiesAtIndex(imageSource, i, nil),
  230. let gifInfo = (properties as NSDictionary)[kCGImagePropertyGIFDictionary as String] as? NSDictionary else
  231. {
  232. return nil
  233. }
  234. gifDuration += frameDuration(from: gifInfo)
  235. }
  236. images.append(Image.kf_image(cgImage: imageRef, scale: scale, refImage: nil))
  237. }
  238. return (images, gifDuration)
  239. }
  240. // Start of kf_animatedImageWithGIFData
  241. let options: NSDictionary = [kCGImageSourceShouldCache as String: true, kCGImageSourceTypeIdentifierHint as String: kUTTypeGIF]
  242. guard let imageSource = CGImageSourceCreateWithData(data as CFData, options) else {
  243. return nil
  244. }
  245. #if os(macOS)
  246. guard let (images, gifDuration) = decode(from: imageSource, for: options) else {
  247. return nil
  248. }
  249. let image = Image(data: data)
  250. image?.kf_images = images
  251. image?.kf_duration = gifDuration
  252. return image
  253. #else
  254. if preloadAll {
  255. guard let (images, gifDuration) = decode(from: imageSource, for: options) else {
  256. return nil
  257. }
  258. let image = Image.kf_animated(with: images, forDuration: duration <= 0.0 ? gifDuration : duration)
  259. image?.kf_animatedImageData = data
  260. return image
  261. } else {
  262. let image = Image(data: data)
  263. image?.kf_animatedImageData = data
  264. image?.kf_imageSource = ImageSource(ref: imageSource)
  265. return image
  266. }
  267. #endif
  268. }
  269. static func kf_image(data: Data, scale: CGFloat, preloadAllGIFData: Bool) -> Image? {
  270. var image: Image?
  271. #if os(macOS)
  272. switch data.kf_imageFormat {
  273. case .JPEG: image = Image(data: data)
  274. case .PNG: image = Image(data: data)
  275. case .GIF: image = Image.kf_animated(with: data, scale: scale, duration: 0.0, preloadAll: preloadAllGIFData)
  276. case .unknown: image = Image(data: data)
  277. }
  278. #else
  279. switch data.kf_imageFormat {
  280. case .JPEG: image = Image(data: data, scale: scale)
  281. case .PNG: image = Image(data: data, scale: scale)
  282. case .GIF: image = Image.kf_animated(with: data, scale: scale, duration: 0.0, preloadAll: preloadAllGIFData)
  283. case .unknown: image = Image(data: data, scale: scale)
  284. }
  285. #endif
  286. return image
  287. }
  288. }
  289. // MARK: - Image Transforming
  290. extension Image {
  291. // MARK: - Round Corner
  292. /// Create a round corner image based on `self`.
  293. ///
  294. /// - parameter radius: The round corner radius of creating image.
  295. /// - parameter size: The target size of creating image.
  296. /// - parameter scale: The image scale of creating 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 kf_image(withRoundRadius radius: CGFloat, fit size: CGSize, scale: CGFloat) -> Image {
  302. guard let cgImage = cgImage else {
  303. assertionFailure("[Kingfisher] Round corder image only works for CG-based image.")
  304. return self
  305. }
  306. let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
  307. return draw(cgImage: cgImage, to: size) {
  308. #if os(macOS)
  309. let path = NSBezierPath(roundedRect: rect, xRadius: radius, yRadius: radius)
  310. path.windingRule = .evenOddWindingRule
  311. path.addClip()
  312. draw(in: rect)
  313. #else
  314. guard let context = UIGraphicsGetCurrentContext() else {
  315. assertionFailure("[Kingfisher] Failed to create CG context for image.")
  316. return
  317. }
  318. let path = UIBezierPath(roundedRect: rect, byRoundingCorners: .allCorners, cornerRadii: CGSize(width: radius, height: radius)).cgPath
  319. context.addPath(path)
  320. context.clip()
  321. draw(in: rect)
  322. #endif
  323. }
  324. }
  325. #if os(iOS) || os(tvOS)
  326. func kf_resize(to size: CGSize, for contentMode: UIViewContentMode) -> Image {
  327. switch contentMode {
  328. case .scaleAspectFit:
  329. let newSize = self.size.kf_constrained(size)
  330. return kf_resize(to: newSize)
  331. case .scaleAspectFill:
  332. let newSize = self.size.kf_filling(size)
  333. return kf_resize(to: newSize)
  334. default:
  335. return kf_resize(to: size)
  336. }
  337. }
  338. #endif
  339. // MARK: - Resize
  340. /// Resize `self` to an image of new size.
  341. ///
  342. /// - parameter size: The target size.
  343. ///
  344. /// - returns: An image with new size.
  345. ///
  346. /// - Note: This method only works for CG-based image.
  347. public func kf_resize(to size: CGSize) -> Image {
  348. guard let cgImage = cgImage?.fixed else {
  349. assertionFailure("[Kingfisher] Resize only works for CG-based image.")
  350. return self
  351. }
  352. let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
  353. return draw(cgImage: cgImage, to: size) {
  354. #if os(macOS)
  355. draw(in: rect, from: NSRect.zero, operation: .copy, fraction: 1.0)
  356. #else
  357. draw(in: rect)
  358. #endif
  359. }
  360. }
  361. // MARK: - Blur
  362. /// Create an image with blur effect based on `self`.
  363. ///
  364. /// - parameter radius: The blur radius should be used when creating blue.
  365. ///
  366. /// - returns: An image with blur effect applied.
  367. ///
  368. /// - Note: This method only works for CG-based image.
  369. public func kf_blurred(withRadius radius: CGFloat) -> Image {
  370. #if os(watchOS)
  371. return self
  372. #else
  373. guard let cgImage = cgImage else {
  374. assertionFailure("[Kingfisher] Blur only works for CG-based image.")
  375. return self
  376. }
  377. // http://www.w3.org/TR/SVG/filters.html#feGaussianBlurElement
  378. // let d = floor(s * 3*sqrt(2*pi)/4 + 0.5)
  379. // if d is odd, use three box-blurs of size 'd', centered on the output pixel.
  380. let s = max(radius, 2.0)
  381. // We will do blur on a resized image (*0.5), so the blur radius could be half as well.
  382. var targetRadius = floor((Double(s * 3.0) * sqrt(2 * M_PI) / 4.0 + 0.5))
  383. if targetRadius.isEven {
  384. targetRadius += 1
  385. }
  386. let iterations: Int
  387. if radius < 0.5 {
  388. iterations = 1
  389. } else if radius < 1.5 {
  390. iterations = 2
  391. } else {
  392. iterations = 3
  393. }
  394. let w = Int(kf_size.width)
  395. let h = Int(kf_size.height)
  396. let rowBytes = Int(CGFloat(cgImage.bytesPerRow))
  397. let inDataPointer = UnsafeMutablePointer<UInt8>.allocate(capacity: rowBytes * Int(h))
  398. inDataPointer.initialize(to: 0)
  399. defer {
  400. inDataPointer.deinitialize()
  401. inDataPointer.deallocate(capacity: rowBytes * Int(h))
  402. }
  403. let bitmapInfo = cgImage.bitmapInfo.fixed
  404. guard let context = CGContext(data: inDataPointer,
  405. width: w,
  406. height: h,
  407. bitsPerComponent: cgImage.bitsPerComponent,
  408. bytesPerRow: rowBytes,
  409. space: cgImage.colorSpace ?? CGColorSpaceCreateDeviceRGB(),
  410. bitmapInfo: bitmapInfo.rawValue) else
  411. {
  412. assertionFailure("[Kingfisher] Failed to create CG context for blurring image.")
  413. return self
  414. }
  415. context.draw(cgImage, in: CGRect(x: 0, y: 0, width: w, height: h))
  416. var inBuffer = vImage_Buffer(data: inDataPointer, height: vImagePixelCount(h), width: vImagePixelCount(w), rowBytes: rowBytes)
  417. let outDataPointer = UnsafeMutablePointer<UInt8>.allocate(capacity: rowBytes * Int(h))
  418. outDataPointer.initialize(to: 0)
  419. defer {
  420. outDataPointer.deinitialize()
  421. outDataPointer.deallocate(capacity: rowBytes * Int(h))
  422. }
  423. var outBuffer = vImage_Buffer(data: outDataPointer, height: vImagePixelCount(h), width: vImagePixelCount(w), rowBytes: rowBytes)
  424. for _ in 0 ..< iterations {
  425. vImageBoxConvolve_ARGB8888(&inBuffer, &outBuffer, nil, 0, 0, UInt32(targetRadius), UInt32(targetRadius), nil, vImage_Flags(kvImageEdgeExtend))
  426. (inBuffer, outBuffer) = (outBuffer, inBuffer)
  427. }
  428. guard let outContext = CGContext(data: inDataPointer,
  429. width: w,
  430. height: h,
  431. bitsPerComponent: cgImage.bitsPerComponent,
  432. bytesPerRow: rowBytes,
  433. space: cgImage.colorSpace ?? CGColorSpaceCreateDeviceRGB(),
  434. bitmapInfo: bitmapInfo.rawValue) else
  435. {
  436. assertionFailure("[Kingfisher] Failed to create CG context for blurring image.")
  437. return self
  438. }
  439. #if os(macOS)
  440. let result = outContext.makeImage().flatMap { kf_fixedForRetinaPixel(cgImage: $0, to: kf_size) }
  441. #else
  442. let result = outContext.makeImage().flatMap { Image(cgImage: $0) }
  443. #endif
  444. guard let blurredImage = result else {
  445. assertionFailure("[Kingfisher] Can not make an blurred image within this context.")
  446. return self
  447. }
  448. return blurredImage
  449. #endif
  450. }
  451. // MARK: - Overlay
  452. /// Create an image from `self` with a color overlay layer.
  453. ///
  454. /// - parameter color: The color should be use to overlay.
  455. /// - parameter fraction: Fraction of input color. From 0.0 to 1.0. 0.0 means solid color, 1.0 means transparent overlay.
  456. ///
  457. /// - returns: An image with a color overlay applied.
  458. ///
  459. /// - Note: This method only works for CG-based image.
  460. public func kf_overlaying(with color: Color, fraction: CGFloat) -> Image {
  461. guard let cgImage = cgImage?.fixed else {
  462. assertionFailure("[Kingfisher] Overlaying only works for CG-based image.")
  463. return self
  464. }
  465. let rect = CGRect(x: 0, y: 0, width: kf_size.width, height: kf_size.height)
  466. return draw(cgImage: cgImage, to: rect.size) {
  467. #if os(macOS)
  468. draw(in: rect)
  469. if fraction > 0 {
  470. color.withAlphaComponent(1 - fraction).set()
  471. NSRectFillUsingOperation(rect, .sourceAtop)
  472. }
  473. #else
  474. color.set()
  475. UIRectFill(rect)
  476. draw(in: rect, blendMode: .destinationIn, alpha: 1.0)
  477. if fraction > 0 {
  478. draw(in: rect, blendMode: .sourceAtop, alpha: fraction)
  479. }
  480. #endif
  481. }
  482. }
  483. // MARK: - Tint
  484. /// Create an image from `self` with a color tint.
  485. ///
  486. /// - parameter color: The color should be used to tint `self`
  487. ///
  488. /// - returns: An image with a color tint applied.
  489. public func kf_tinted(with color: Color) -> Image {
  490. #if os(watchOS)
  491. return self
  492. #else
  493. return kf_apply(.tint(color))
  494. #endif
  495. }
  496. // MARK: - Color Control
  497. /// Create an image from `self` with color control.
  498. ///
  499. /// - parameter brightness: Brightness changing to image.
  500. /// - parameter contrast: Contrast changing to image.
  501. /// - parameter saturation: Saturation changing to image.
  502. /// - parameter inputEV: InputEV changing to image.
  503. ///
  504. /// - returns: An image with color control applied.
  505. public func kf_adjusted(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) -> Image {
  506. #if os(watchOS)
  507. return self
  508. #else
  509. return kf_apply(.colorControl(brightness, contrast, saturation, inputEV))
  510. #endif
  511. }
  512. }
  513. // MARK: - Decode
  514. extension Image {
  515. func kf_decoded() -> Image? {
  516. return self.kf_decoded(scale: kf_scale)
  517. }
  518. func kf_decoded(scale: CGFloat) -> Image {
  519. // prevent animated image (GIF) lose it's images
  520. #if os(iOS)
  521. if kf_imageSource != nil { return self }
  522. #else
  523. if kf_images != nil { return self }
  524. #endif
  525. guard let imageRef = self.cgImage else {
  526. assertionFailure("[Kingfisher] Decoding only works for CG-based image.")
  527. return self
  528. }
  529. let colorSpace = CGColorSpaceCreateDeviceRGB()
  530. let bitmapInfo = imageRef.bitmapInfo.fixed
  531. guard let context = CGContext(data: nil, width: imageRef.width, height: imageRef.height, bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: bitmapInfo.rawValue) else {
  532. assertionFailure("[Kingfisher] Decoding fails to create a valid context.")
  533. return self
  534. }
  535. let rect = CGRect(x: 0, y: 0, width: imageRef.width, height: imageRef.height)
  536. context.draw(imageRef, in: rect)
  537. let decompressedImageRef = context.makeImage()
  538. return Image.kf_image(cgImage: decompressedImageRef!, scale: scale, refImage: self)
  539. }
  540. }
  541. /// Reference the source image reference
  542. class ImageSource {
  543. var imageRef: CGImageSource?
  544. init(ref: CGImageSource) {
  545. self.imageRef = ref
  546. }
  547. }
  548. // MARK: - Image format
  549. private struct ImageHeaderData {
  550. static var PNG: [UInt8] = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]
  551. static var JPEG_SOI: [UInt8] = [0xFF, 0xD8]
  552. static var JPEG_IF: [UInt8] = [0xFF]
  553. static var GIF: [UInt8] = [0x47, 0x49, 0x46]
  554. }
  555. enum ImageFormat {
  556. case unknown, PNG, JPEG, GIF
  557. }
  558. // MARK: - Misc Helpers
  559. extension Data {
  560. var kf_imageFormat: ImageFormat {
  561. var buffer = [UInt8](repeating: 0, count: 8)
  562. (self as NSData).getBytes(&buffer, length: 8)
  563. if buffer == ImageHeaderData.PNG {
  564. return .PNG
  565. } else if buffer[0] == ImageHeaderData.JPEG_SOI[0] &&
  566. buffer[1] == ImageHeaderData.JPEG_SOI[1] &&
  567. buffer[2] == ImageHeaderData.JPEG_IF[0]
  568. {
  569. return .JPEG
  570. } else if buffer[0] == ImageHeaderData.GIF[0] &&
  571. buffer[1] == ImageHeaderData.GIF[1] &&
  572. buffer[2] == ImageHeaderData.GIF[2]
  573. {
  574. return .GIF
  575. }
  576. return .unknown
  577. }
  578. }
  579. extension CGSize {
  580. func kf_constrained(_ size: CGSize) -> CGSize {
  581. let aspectWidth = round(kf_aspectRatio * size.height)
  582. let aspectHeight = round(size.width / kf_aspectRatio)
  583. return aspectWidth > size.width ? CGSize(width: size.width, height: aspectHeight) : CGSize(width: aspectWidth, height: size.height)
  584. }
  585. func kf_filling(_ size: CGSize) -> CGSize {
  586. let aspectWidth = round(kf_aspectRatio * size.height)
  587. let aspectHeight = round(size.width / kf_aspectRatio)
  588. return aspectWidth < size.width ? CGSize(width: size.width, height: aspectHeight) : CGSize(width: aspectWidth, height: size.height)
  589. }
  590. private var kf_aspectRatio: CGFloat {
  591. return height == 0.0 ? 1.0 : width / height
  592. }
  593. }
  594. extension CGImage {
  595. var isARGB8888: Bool {
  596. return bitsPerPixel == 32 && bitsPerComponent == 8 && bitmapInfo.contains(.alphaInfoMask)
  597. }
  598. var fixed: CGImage {
  599. if isARGB8888 { return self }
  600. // Convert to ARGB if it isn't
  601. guard let context = CGContext.createARGBContext(from: self) else {
  602. assertionFailure("[Kingfisher] Failed to create CG context when converting non ARGB image.")
  603. return self
  604. }
  605. context.draw(self, in: CGRect(x: 0, y: 0, width: width, height: height))
  606. guard let r = context.makeImage() else {
  607. assertionFailure("[Kingfisher] Failed to create CG image when converting non ARGB image.")
  608. return self
  609. }
  610. return r
  611. }
  612. }
  613. extension CGBitmapInfo {
  614. var fixed: CGBitmapInfo {
  615. var fixed = self
  616. let alpha = (rawValue & CGBitmapInfo.alphaInfoMask.rawValue)
  617. if alpha == CGImageAlphaInfo.none.rawValue {
  618. fixed.remove(.alphaInfoMask)
  619. fixed = CGBitmapInfo(rawValue: fixed.rawValue | CGImageAlphaInfo.noneSkipFirst.rawValue)
  620. } else if !(alpha == CGImageAlphaInfo.noneSkipFirst.rawValue) || !(alpha == CGImageAlphaInfo.noneSkipLast.rawValue) {
  621. fixed.remove(.alphaInfoMask)
  622. fixed = CGBitmapInfo(rawValue: fixed.rawValue | CGImageAlphaInfo.premultipliedFirst.rawValue)
  623. }
  624. return fixed
  625. }
  626. }
  627. extension Image {
  628. func draw(cgImage: CGImage?, to size: CGSize, draw: ()->()) -> Image {
  629. #if os(macOS)
  630. guard let rep = NSBitmapImageRep(
  631. bitmapDataPlanes: nil,
  632. pixelsWide: Int(size.width),
  633. pixelsHigh: Int(size.height),
  634. bitsPerSample: cgImage?.bitsPerComponent ?? 8,
  635. samplesPerPixel: 4,
  636. hasAlpha: true,
  637. isPlanar: false,
  638. colorSpaceName: NSCalibratedRGBColorSpace,
  639. bytesPerRow: 0,
  640. bitsPerPixel: 0) else
  641. {
  642. assertionFailure("[Kingfisher] Image representation cannot be created.")
  643. return self
  644. }
  645. rep.size = size
  646. NSGraphicsContext.saveGraphicsState()
  647. let context = NSGraphicsContext(bitmapImageRep: rep)
  648. NSGraphicsContext.setCurrent(context)
  649. draw()
  650. NSGraphicsContext.restoreGraphicsState()
  651. let outputImage = Image(size: size)
  652. outputImage.addRepresentation(rep)
  653. return outputImage
  654. #else
  655. UIGraphicsBeginImageContextWithOptions(size, false, scale)
  656. defer { UIGraphicsEndImageContext() }
  657. draw()
  658. return UIGraphicsGetImageFromCurrentImageContext() ?? self
  659. #endif
  660. }
  661. #if os(macOS)
  662. func kf_fixedForRetinaPixel(cgImage: CGImage, to size: CGSize) -> Image {
  663. let image = Image(cgImage: cgImage, size: self.size)
  664. let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
  665. return draw(cgImage: cgImage, to: kf_size) {
  666. image.draw(in: rect, from: NSRect.zero, operation: .copy, fraction: 1.0)
  667. }
  668. }
  669. #endif
  670. }
  671. extension CGContext {
  672. static func createARGBContext(from imageRef: CGImage) -> CGContext? {
  673. let w = imageRef.width
  674. let h = imageRef.height
  675. let bytesPerRow = w * 4
  676. let colorSpace = CGColorSpaceCreateDeviceRGB()
  677. let data = malloc(bytesPerRow * h)
  678. defer {
  679. free(data)
  680. }
  681. let bitmapInfo = imageRef.bitmapInfo.fixed
  682. // Create the bitmap context. We want pre-multiplied ARGB, 8-bits
  683. // per component. Regardless of what the source image format is
  684. // (CMYK, Grayscale, and so on) it will be converted over to the format
  685. // specified here.
  686. return CGContext(data: data,
  687. width: w,
  688. height: h,
  689. bitsPerComponent: imageRef.bitsPerComponent,
  690. bytesPerRow: bytesPerRow,
  691. space: colorSpace,
  692. bitmapInfo: bitmapInfo.rawValue)
  693. }
  694. }
  695. extension Double {
  696. var isEven: Bool {
  697. return truncatingRemainder(dividingBy: 2.0) == 0
  698. }
  699. }