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