Image.swift 27 KB

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