Image.swift 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786
  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_animatedImage(images: [Image], duration: 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 Image.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. if let cgimage = cgImage {
  155. let rep = NSBitmapImageRep(cgImage: cgimage)
  156. return rep.representation(using: .PNG, properties: [:])
  157. }
  158. return nil
  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. func gifRepresentation(duration: TimeInterval, repeatCount: Int) -> Data? {
  184. guard let images = kf_images else {
  185. return nil
  186. }
  187. let frameCount = images.count
  188. let gifDuration = duration <= 0.0 ? kf_duration / Double(frameCount) : duration / Double(frameCount)
  189. let frameProperties = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFDelayTime as String: gifDuration]]
  190. let imageProperties = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFLoopCount as String: repeatCount]]
  191. let data = NSMutableData()
  192. guard let destination = CGImageDestinationCreateWithData(data, kUTTypeGIF, frameCount, nil) else {
  193. return nil
  194. }
  195. CGImageDestinationSetProperties(destination, imageProperties as CFDictionary)
  196. for image in images {
  197. CGImageDestinationAddImage(destination, image.cgImage!, frameProperties as CFDictionary)
  198. }
  199. return CGImageDestinationFinalize(destination) ? data.copy() as? Data : nil
  200. }
  201. }
  202. // MARK: - Create images from data
  203. extension Image {
  204. static func kf_animated(with data: Data, preloadAll: Bool) -> Image? {
  205. return kf_animated(with: data, scale: 1.0, duration: 0.0, preloadAll: preloadAll)
  206. }
  207. static func kf_animated(with data: Data, scale: CGFloat, duration: TimeInterval, preloadAll: Bool) -> Image? {
  208. func decode(from imageSource: CGImageSource, for options: NSDictionary) -> ([Image], TimeInterval)? {
  209. //Calculates frame duration for a gif frame out of the kCGImagePropertyGIFDictionary dictionary
  210. func frameDuration(from gifInfo: NSDictionary) -> Double {
  211. let gifDefaultFrameDuration = 0.100
  212. let unclampedDelayTime = gifInfo[kCGImagePropertyGIFUnclampedDelayTime as String] as? NSNumber
  213. let delayTime = gifInfo[kCGImagePropertyGIFDelayTime as String] as? NSNumber
  214. let duration = unclampedDelayTime ?? delayTime
  215. guard let frameDuration = duration else { return gifDefaultFrameDuration }
  216. return frameDuration.doubleValue > 0.011 ? frameDuration.doubleValue : gifDefaultFrameDuration
  217. }
  218. let frameCount = CGImageSourceGetCount(imageSource)
  219. var images = [Image]()
  220. var gifDuration = 0.0
  221. for i in 0 ..< frameCount {
  222. guard let imageRef = CGImageSourceCreateImageAtIndex(imageSource, i, options) else {
  223. return nil
  224. }
  225. if frameCount == 1 {
  226. // Single frame
  227. gifDuration = Double.infinity
  228. } else {
  229. // Animated GIF
  230. guard let properties = CGImageSourceCopyPropertiesAtIndex(imageSource, i, nil),
  231. let gifInfo = (properties as NSDictionary)[kCGImagePropertyGIFDictionary as String] as? NSDictionary else
  232. {
  233. return nil
  234. }
  235. gifDuration += frameDuration(from: gifInfo)
  236. }
  237. images.append(Image.kf_image(cgImage: imageRef, scale: scale, refImage: nil))
  238. }
  239. return (images, gifDuration)
  240. }
  241. // Start of kf_animatedImageWithGIFData
  242. let options: NSDictionary = [kCGImageSourceShouldCache as String: true, kCGImageSourceTypeIdentifierHint as String: kUTTypeGIF]
  243. guard let imageSource = CGImageSourceCreateWithData(data as CFData, options) else {
  244. return nil
  245. }
  246. #if os(macOS)
  247. guard let (images, gifDuration) = decode(from: imageSource, for: options) else {
  248. return nil
  249. }
  250. let image = Image(data: data)
  251. image?.kf_images = images
  252. image?.kf_duration = gifDuration
  253. return image
  254. #else
  255. if preloadAll {
  256. guard let (images, gifDuration) = decode(from: imageSource, for: options) else {
  257. return nil
  258. }
  259. let image = Image.kf_animated(with: images, forDuration: duration <= 0.0 ? gifDuration : duration)
  260. image?.kf_animatedImageData = data
  261. return image
  262. } else {
  263. let image = Image(data: data)
  264. image?.kf_animatedImageData = data
  265. image?.kf_imageSource = ImageSource(ref: imageSource)
  266. return image
  267. }
  268. #endif
  269. }
  270. static func kf_image(data: Data, scale: CGFloat, preloadAllGIFData: Bool) -> Image? {
  271. var image: Image?
  272. #if os(macOS)
  273. switch data.kf_imageFormat {
  274. case .JPEG: image = Image(data: data)
  275. case .PNG: image = Image(data: data)
  276. case .GIF: image = Image.kf_animated(with: data, scale: scale, duration: 0.0, preloadAll: preloadAllGIFData)
  277. case .unknown: image = Image(data: data)
  278. }
  279. #else
  280. switch data.kf_imageFormat {
  281. case .JPEG: image = Image(data: data, scale: scale)
  282. case .PNG: image = Image(data: data, scale: scale)
  283. case .GIF: image = Image.kf_animated(with: data, scale: scale, duration: 0.0, preloadAll: preloadAllGIFData)
  284. case .unknown: image = Image(data: data, scale: scale)
  285. }
  286. #endif
  287. return image
  288. }
  289. }
  290. // MARK: - Image Transforming
  291. extension Image {
  292. // MARK: - Round Corner
  293. public func kf_image(withRoundRadius radius: CGFloat, fit size: CGSize, scale: CGFloat) -> Image {
  294. let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
  295. #if os(macOS)
  296. guard let cgImage = cgImage else {
  297. assertionFailure("[Kingfisher] Round corder image only works for CG-based image.")
  298. return self
  299. }
  300. return draw(cgImage: cgImage, to: size) {
  301. let path = NSBezierPath(roundedRect: rect, xRadius: radius, yRadius: radius)
  302. path.windingRule = .evenOddWindingRule
  303. path.addClip()
  304. draw(in: rect)
  305. }
  306. #else
  307. return draw(cgImage: nil, to: size) {
  308. guard let context = UIGraphicsGetCurrentContext() else {
  309. assertionFailure("[Kingfisher] Failed to create CG context for image.")
  310. return
  311. }
  312. let path = UIBezierPath(roundedRect: rect, byRoundingCorners: .allCorners, cornerRadii: CGSize(width: radius, height: radius)).cgPath
  313. context.addPath(path)
  314. context.clip()
  315. draw(in: rect)
  316. }
  317. #endif
  318. }
  319. #if os(iOS) || os(tvOS)
  320. func kf_resize(to size: CGSize, for contentMode: UIViewContentMode) -> Image {
  321. switch contentMode {
  322. case .scaleAspectFit:
  323. let newSize = self.size.kf_constrained(size)
  324. return kf_resize(to: newSize)
  325. case .scaleAspectFill:
  326. let newSize = self.size.kf_filling(size)
  327. return kf_resize(to: newSize)
  328. default:
  329. return kf_resize(to: size)
  330. }
  331. }
  332. #endif
  333. // MARK: - Resize
  334. public func kf_resize(to size: CGSize) -> Image {
  335. let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
  336. #if os(macOS)
  337. guard let cgImage = cgImage?.fixed else {
  338. assertionFailure("[Kingfisher] Resize only works for CG-based image.")
  339. return self
  340. }
  341. return draw(cgImage: cgImage, to: size, draw: {
  342. draw(in: rect, from: NSRect.zero, operation: .copy, fraction: 1.0)
  343. })
  344. #else
  345. return draw(cgImage: nil, to: size) {
  346. draw(in: rect)
  347. }
  348. #endif
  349. }
  350. // MARK: - Blur
  351. public func kf_blurred(withRadius radius: CGFloat) -> Image {
  352. #if os(watchOS)
  353. return self
  354. #else
  355. guard let cgImage = cgImage else {
  356. assertionFailure("[Kingfisher] Blur only works for CG-based image.")
  357. return self
  358. }
  359. // http://www.w3.org/TR/SVG/filters.html#feGaussianBlurElement
  360. // let d = floor(s * 3*sqrt(2*pi)/4 + 0.5)
  361. // if d is odd, use three box-blurs of size 'd', centered on the output pixel.
  362. let s = max(radius, 2.0)
  363. // We will do blur on a resized image (*0.5), so the blur radius could be half as well.
  364. var targetRadius = floor((Double(s * 3.0) * sqrt(2 * M_PI) / 4.0 + 0.5))
  365. if targetRadius.isEven {
  366. targetRadius += 1
  367. }
  368. let iterations: Int
  369. if radius < 0.5 {
  370. iterations = 1
  371. } else if radius < 1.5 {
  372. iterations = 2
  373. } else {
  374. iterations = 3
  375. }
  376. let w = Int(kf_size.width)
  377. let h = Int(kf_size.height)
  378. let rowBytes = Int(CGFloat(cgImage.bytesPerRow))
  379. let inDataPointer = UnsafeMutablePointer<UInt8>.allocate(capacity: rowBytes * Int(h))
  380. inDataPointer.initialize(to: 0)
  381. defer {
  382. inDataPointer.deinitialize()
  383. inDataPointer.deallocate(capacity: rowBytes * Int(h))
  384. }
  385. let bitmapInfo = cgImage.bitmapInfo.fixed
  386. guard let context = CGContext(data: inDataPointer,
  387. width: w,
  388. height: h,
  389. bitsPerComponent: cgImage.bitsPerComponent,
  390. bytesPerRow: rowBytes,
  391. space: cgImage.colorSpace ?? CGColorSpaceCreateDeviceRGB(),
  392. bitmapInfo: bitmapInfo.rawValue) else
  393. {
  394. assertionFailure("[Kingfisher] Failed to create CG context for blurring image.")
  395. return self
  396. }
  397. context.draw(cgImage, in: CGRect(x: 0, y: 0, width: w, height: h))
  398. var inBuffer = vImage_Buffer(data: inDataPointer, height: vImagePixelCount(h), width: vImagePixelCount(w), rowBytes: rowBytes)
  399. let outDataPointer = UnsafeMutablePointer<UInt8>.allocate(capacity: rowBytes * Int(h))
  400. outDataPointer.initialize(to: 0)
  401. defer {
  402. outDataPointer.deinitialize()
  403. outDataPointer.deallocate(capacity: rowBytes * Int(h))
  404. }
  405. var outBuffer = vImage_Buffer(data: outDataPointer, height: vImagePixelCount(h), width: vImagePixelCount(w), rowBytes: rowBytes)
  406. for _ in 0 ..< iterations {
  407. vImageBoxConvolve_ARGB8888(&inBuffer, &outBuffer, nil, 0, 0, UInt32(targetRadius), UInt32(targetRadius), nil, vImage_Flags(kvImageEdgeExtend))
  408. (inBuffer, outBuffer) = (outBuffer, inBuffer)
  409. }
  410. guard let outContext = CGContext(data: inDataPointer,
  411. width: w,
  412. height: h,
  413. bitsPerComponent: cgImage.bitsPerComponent,
  414. bytesPerRow: rowBytes,
  415. space: cgImage.colorSpace ?? CGColorSpaceCreateDeviceRGB(),
  416. bitmapInfo: bitmapInfo.rawValue) else
  417. {
  418. assertionFailure("[Kingfisher] Failed to create CG context for blurring image.")
  419. return self
  420. }
  421. #if os(macOS)
  422. let result = outContext.makeImage().flatMap { kf_fixedForRetinaPixel(cgImage: $0, to: kf_size) }
  423. #else
  424. let result = outContext.makeImage().flatMap { Image(cgImage: $0) }
  425. #endif
  426. guard let blurredImage = result else {
  427. assertionFailure("[Kingfisher] Can not make an resized image within context.")
  428. return self
  429. }
  430. return blurredImage
  431. #endif
  432. }
  433. // MARK: - Overlay
  434. public func kf_overlaying(with color: Color, fraction: CGFloat) -> Image {
  435. let rect = CGRect(x: 0, y: 0, width: kf_size.width, height: kf_size.height)
  436. #if os(macOS)
  437. guard let cgImage = cgImage?.fixed else {
  438. assertionFailure("[Kingfisher] Resize only works for CG-based image.")
  439. return self
  440. }
  441. return draw(cgImage: cgImage, to: rect.size, draw: {
  442. draw(in: rect)
  443. color.withAlphaComponent(1 - fraction).set()
  444. NSRectFillUsingOperation(rect, .sourceAtop)
  445. })
  446. #else
  447. return draw(cgImage: nil, to: size) {
  448. color.set()
  449. UIRectFill(rect)
  450. draw(in: rect, blendMode: .destinationIn, alpha: 1.0)
  451. if fraction > 0 {
  452. draw(in: rect, blendMode: .sourceAtop, alpha: fraction)
  453. }
  454. }
  455. #endif
  456. }
  457. // MARK: - Tint
  458. public func kf_tinted(with color: Color) -> Image {
  459. #if os(watchOS)
  460. return self
  461. #else
  462. return kf_apply(.tint(color))
  463. #endif
  464. }
  465. // MARK: - Color Control
  466. public func kf_adjusted(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) -> Image {
  467. #if os(watchOS)
  468. return self
  469. #else
  470. return kf_apply(.colorControl(brightness, contrast, saturation, inputEV))
  471. #endif
  472. }
  473. }
  474. // MARK: - Decode
  475. extension Image {
  476. func kf_decoded() -> Image? {
  477. return self.kf_decoded(scale: kf_scale)
  478. }
  479. func kf_decoded(scale: CGFloat) -> Image? {
  480. // prevent animated image (GIF) lose it's images
  481. #if os(iOS)
  482. if kf_imageSource != nil { return self }
  483. #else
  484. if kf_images != nil { return self }
  485. #endif
  486. guard let imageRef = self.cgImage else {
  487. assertionFailure("[Kingfisher] Decoding only works for CG-based image.")
  488. return nil
  489. }
  490. let colorSpace = CGColorSpaceCreateDeviceRGB()
  491. let bitmapInfo = imageRef.bitmapInfo.fixed
  492. let context = CGContext(data: nil, width: imageRef.width, height: imageRef.height, bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: bitmapInfo.rawValue)
  493. if let context = context {
  494. let rect = CGRect(x: 0, y: 0, width: imageRef.width, height: imageRef.height)
  495. context.draw(imageRef, in: rect)
  496. let decompressedImageRef = context.makeImage()
  497. return Image.kf_image(cgImage: decompressedImageRef!, scale: scale, refImage: self)
  498. } else {
  499. return nil
  500. }
  501. }
  502. }
  503. /// Reference the source image reference
  504. class ImageSource {
  505. var imageRef: CGImageSource?
  506. init(ref: CGImageSource) {
  507. self.imageRef = ref
  508. }
  509. }
  510. // MARK: - Image format
  511. private struct ImageHeaderData {
  512. static var PNG: [UInt8] = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]
  513. static var JPEG_SOI: [UInt8] = [0xFF, 0xD8]
  514. static var JPEG_IF: [UInt8] = [0xFF]
  515. static var GIF: [UInt8] = [0x47, 0x49, 0x46]
  516. }
  517. enum ImageFormat {
  518. case unknown, PNG, JPEG, GIF
  519. }
  520. // MARK: - Misc Helpers
  521. extension Data {
  522. var kf_imageFormat: ImageFormat {
  523. var buffer = [UInt8](repeating: 0, count: 8)
  524. (self as NSData).getBytes(&buffer, length: 8)
  525. if buffer == ImageHeaderData.PNG {
  526. return .PNG
  527. } else if buffer[0] == ImageHeaderData.JPEG_SOI[0] &&
  528. buffer[1] == ImageHeaderData.JPEG_SOI[1] &&
  529. buffer[2] == ImageHeaderData.JPEG_IF[0]
  530. {
  531. return .JPEG
  532. } else if buffer[0] == ImageHeaderData.GIF[0] &&
  533. buffer[1] == ImageHeaderData.GIF[1] &&
  534. buffer[2] == ImageHeaderData.GIF[2]
  535. {
  536. return .GIF
  537. }
  538. return .unknown
  539. }
  540. }
  541. extension CGSize {
  542. func kf_constrained(_ size: CGSize) -> CGSize {
  543. let aspectWidth = round(kf_aspectRatio * size.height)
  544. let aspectHeight = round(size.width / kf_aspectRatio)
  545. return aspectWidth > size.width ? CGSize(width: size.width, height: aspectHeight) : CGSize(width: aspectWidth, height: size.height)
  546. }
  547. func kf_filling(_ size: CGSize) -> CGSize {
  548. let aspectWidth = round(kf_aspectRatio * size.height)
  549. let aspectHeight = round(size.width / kf_aspectRatio)
  550. return aspectWidth < size.width ? CGSize(width: size.width, height: aspectHeight) : CGSize(width: aspectWidth, height: size.height)
  551. }
  552. private var kf_aspectRatio: CGFloat {
  553. return height == 0.0 ? 1.0 : width / height
  554. }
  555. }
  556. extension CGImage {
  557. var isARGB8888: Bool {
  558. return bitsPerPixel == 32 && bitsPerComponent == 8 && bitmapInfo.contains(.alphaInfoMask)
  559. }
  560. var fixed: CGImage {
  561. if isARGB8888 { return self }
  562. // Convert to ARGB if it isn't
  563. guard let context = CGContext.createARGBContext(from: self) else {
  564. assertionFailure("[Kingfisher] Failed to create CG context when converting non ARGB image.")
  565. return self
  566. }
  567. context.draw(self, in: CGRect(x: 0, y: 0, width: width, height: height))
  568. guard let r = context.makeImage() else {
  569. assertionFailure("[Kingfisher] Failed to create CG image when converting non ARGB image.")
  570. return self
  571. }
  572. return r
  573. }
  574. }
  575. extension CGBitmapInfo {
  576. var fixed: CGBitmapInfo {
  577. var fixed = self
  578. let alpha = (rawValue & CGBitmapInfo.alphaInfoMask.rawValue)
  579. if alpha == CGImageAlphaInfo.none.rawValue {
  580. fixed.remove(.alphaInfoMask)
  581. fixed = CGBitmapInfo(rawValue: fixed.rawValue | CGImageAlphaInfo.noneSkipFirst.rawValue)
  582. } else if !(alpha == CGImageAlphaInfo.noneSkipFirst.rawValue) || !(alpha == CGImageAlphaInfo.noneSkipLast.rawValue) {
  583. fixed.remove(.alphaInfoMask)
  584. fixed = CGBitmapInfo(rawValue: fixed.rawValue | CGImageAlphaInfo.premultipliedFirst.rawValue)
  585. }
  586. return fixed
  587. }
  588. }
  589. extension Image {
  590. func draw(cgImage: CGImage?, to size: CGSize, draw: ()->()) -> Image {
  591. #if os(macOS)
  592. guard let rep = NSBitmapImageRep(
  593. bitmapDataPlanes: nil,
  594. pixelsWide: Int(size.width),
  595. pixelsHigh: Int(size.height),
  596. bitsPerSample: cgImage?.bitsPerComponent ?? 8,
  597. samplesPerPixel: 4,
  598. hasAlpha: true,
  599. isPlanar: false,
  600. colorSpaceName: NSCalibratedRGBColorSpace,
  601. bytesPerRow: 0,
  602. bitsPerPixel: 0) else
  603. {
  604. assertionFailure("[Kingfisher] Image representation cannot be created.")
  605. return self
  606. }
  607. rep.size = size
  608. NSGraphicsContext.saveGraphicsState()
  609. let context = NSGraphicsContext(bitmapImageRep: rep)
  610. NSGraphicsContext.setCurrent(context)
  611. draw()
  612. NSGraphicsContext.restoreGraphicsState()
  613. let outputImage = Image(size: size)
  614. outputImage.addRepresentation(rep)
  615. return outputImage
  616. #else
  617. UIGraphicsBeginImageContextWithOptions(size, false, scale)
  618. defer { UIGraphicsEndImageContext() }
  619. draw()
  620. return UIGraphicsGetImageFromCurrentImageContext() ?? self
  621. #endif
  622. }
  623. #if os(macOS)
  624. func kf_fixedForRetinaPixel(cgImage: CGImage, to size: CGSize) -> Image {
  625. let image = Image(cgImage: cgImage, size: self.size)
  626. let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
  627. return draw(cgImage: cgImage, to: kf_size) {
  628. image.draw(in: rect, from: NSRect.zero, operation: .copy, fraction: 1.0)
  629. }
  630. }
  631. #endif
  632. }
  633. extension CGContext {
  634. static func createARGBContext(from imageRef: CGImage) -> CGContext? {
  635. let w = imageRef.width
  636. let h = imageRef.height
  637. let bytesPerRow = w * 4
  638. let colorSpace = CGColorSpaceCreateDeviceRGB()
  639. let data = malloc(bytesPerRow * h)
  640. defer {
  641. free(data)
  642. }
  643. let bitmapInfo = imageRef.bitmapInfo.fixed
  644. // Create the bitmap context. We want pre-multiplied ARGB, 8-bits
  645. // per component. Regardless of what the source image format is
  646. // (CMYK, Grayscale, and so on) it will be converted over to the format
  647. // specified here.
  648. return CGContext(data: data,
  649. width: w,
  650. height: h,
  651. bitsPerComponent: imageRef.bitsPerComponent,
  652. bytesPerRow: bytesPerRow,
  653. space: colorSpace,
  654. bitmapInfo: bitmapInfo.rawValue)
  655. }
  656. }
  657. extension Double {
  658. var isEven: Bool {
  659. return truncatingRemainder(dividingBy: 2.0) == 0
  660. }
  661. }