Image.swift 33 KB

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