Image.swift 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946
  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. public 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. public 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. public 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. let 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. ///
  296. /// - returns: An image with round corner of `self`.
  297. ///
  298. /// - Note: This method only works for CG-based image.
  299. public func image(withRoundRadius radius: CGFloat, fit size: CGSize) -> Image {
  300. guard let cgImage = cgImage else {
  301. assertionFailure("[Kingfisher] Round corder image only works for CG-based image.")
  302. return base
  303. }
  304. let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
  305. return draw(cgImage: cgImage, to: size) {
  306. #if os(macOS)
  307. let path = NSBezierPath(roundedRect: rect, xRadius: radius, yRadius: radius)
  308. path.windingRule = .evenOddWindingRule
  309. path.addClip()
  310. base.draw(in: rect)
  311. #else
  312. guard let context = UIGraphicsGetCurrentContext() else {
  313. assertionFailure("[Kingfisher] Failed to create CG context for image.")
  314. return
  315. }
  316. let path = UIBezierPath(roundedRect: rect, byRoundingCorners: .allCorners, cornerRadii: CGSize(width: radius, height: radius)).cgPath
  317. context.addPath(path)
  318. context.clip()
  319. base.draw(in: rect)
  320. #endif
  321. }
  322. }
  323. #if os(iOS) || os(tvOS)
  324. func resize(to size: CGSize, for contentMode: UIViewContentMode) -> Image {
  325. switch contentMode {
  326. case .scaleAspectFit:
  327. let newSize = self.size.kf.constrained(size)
  328. return resize(to: newSize)
  329. case .scaleAspectFill:
  330. let newSize = self.size.kf.filling(size)
  331. return resize(to: newSize)
  332. default:
  333. return resize(to: size)
  334. }
  335. }
  336. #endif
  337. // MARK: - Resize
  338. /// Resize `self` to an image of new size.
  339. ///
  340. /// - parameter size: The target size.
  341. ///
  342. /// - returns: An image with new size.
  343. ///
  344. /// - Note: This method only works for CG-based image.
  345. public func resize(to size: CGSize) -> Image {
  346. guard let cgImage = cgImage else {
  347. assertionFailure("[Kingfisher] Resize only works for CG-based image.")
  348. return base
  349. }
  350. let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
  351. return draw(cgImage: cgImage, to: size) {
  352. #if os(macOS)
  353. base.draw(in: rect, from: NSRect.zero, operation: .copy, fraction: 1.0)
  354. #else
  355. base.draw(in: rect)
  356. #endif
  357. }
  358. }
  359. // MARK: - Blur
  360. /// Create an image with blur effect based on `self`.
  361. ///
  362. /// - parameter radius: The blur radius should be used when creating blue.
  363. ///
  364. /// - returns: An image with blur effect applied.
  365. ///
  366. /// - Note: This method only works for CG-based image.
  367. public func blurred(withRadius radius: CGFloat) -> Image {
  368. #if os(watchOS)
  369. return base
  370. #else
  371. guard let cgImage = cgImage else {
  372. assertionFailure("[Kingfisher] Blur only works for CG-based image.")
  373. return base
  374. }
  375. // http://www.w3.org/TR/SVG/filters.html#feGaussianBlurElement
  376. // let d = floor(s * 3*sqrt(2*pi)/4 + 0.5)
  377. // if d is odd, use three box-blurs of size 'd', centered on the output pixel.
  378. let s = max(radius, 2.0)
  379. // We will do blur on a resized image (*0.5), so the blur radius could be half as well.
  380. var targetRadius = floor((Double(s * 3.0) * sqrt(2 * M_PI) / 4.0 + 0.5))
  381. if targetRadius.isEven {
  382. targetRadius += 1
  383. }
  384. let iterations: Int
  385. if radius < 0.5 {
  386. iterations = 1
  387. } else if radius < 1.5 {
  388. iterations = 2
  389. } else {
  390. iterations = 3
  391. }
  392. let w = Int(size.width)
  393. let h = Int(size.height)
  394. let rowBytes = Int(CGFloat(cgImage.bytesPerRow))
  395. let inDataPointer = UnsafeMutablePointer<UInt8>.allocate(capacity: rowBytes * Int(h))
  396. inDataPointer.initialize(to: 0)
  397. defer {
  398. inDataPointer.deinitialize()
  399. inDataPointer.deallocate(capacity: rowBytes * Int(h))
  400. }
  401. let bitmapInfo = cgImage.bitmapInfo.fixed
  402. guard let context = CGContext(data: inDataPointer,
  403. width: w,
  404. height: h,
  405. bitsPerComponent: cgImage.bitsPerComponent,
  406. bytesPerRow: rowBytes,
  407. space: cgImage.colorSpace ?? CGColorSpaceCreateDeviceRGB(),
  408. bitmapInfo: bitmapInfo.rawValue) else
  409. {
  410. assertionFailure("[Kingfisher] Failed to create CG context for blurring image.")
  411. return base
  412. }
  413. context.draw(cgImage, in: CGRect(x: 0, y: 0, width: w, height: h))
  414. var inBuffer = vImage_Buffer(data: inDataPointer, height: vImagePixelCount(h), width: vImagePixelCount(w), rowBytes: rowBytes)
  415. let outDataPointer = UnsafeMutablePointer<UInt8>.allocate(capacity: rowBytes * Int(h))
  416. outDataPointer.initialize(to: 0)
  417. defer {
  418. outDataPointer.deinitialize()
  419. outDataPointer.deallocate(capacity: rowBytes * Int(h))
  420. }
  421. var outBuffer = vImage_Buffer(data: outDataPointer, height: vImagePixelCount(h), width: vImagePixelCount(w), rowBytes: rowBytes)
  422. for _ in 0 ..< iterations {
  423. vImageBoxConvolve_ARGB8888(&inBuffer, &outBuffer, nil, 0, 0, UInt32(targetRadius), UInt32(targetRadius), nil, vImage_Flags(kvImageEdgeExtend))
  424. (inBuffer, outBuffer) = (outBuffer, inBuffer)
  425. }
  426. guard let outContext = CGContext(data: inDataPointer,
  427. width: w,
  428. height: h,
  429. bitsPerComponent: cgImage.bitsPerComponent,
  430. bytesPerRow: rowBytes,
  431. space: cgImage.colorSpace ?? CGColorSpaceCreateDeviceRGB(),
  432. bitmapInfo: bitmapInfo.rawValue) else
  433. {
  434. assertionFailure("[Kingfisher] Failed to create CG context for blurring image.")
  435. return base
  436. }
  437. #if os(macOS)
  438. let result = outContext.makeImage().flatMap { fixedForRetinaPixel(cgImage: $0, to: size) }
  439. #else
  440. let result = outContext.makeImage().flatMap { Image(cgImage: $0, scale: base.scale, orientation: base.imageOrientation) }
  441. #endif
  442. guard let blurredImage = result else {
  443. assertionFailure("[Kingfisher] Can not make an blurred image within this context.")
  444. return base
  445. }
  446. return blurredImage
  447. #endif
  448. }
  449. // MARK: - Overlay
  450. /// Create an image from `self` with a color overlay layer.
  451. ///
  452. /// - parameter color: The color should be use to overlay.
  453. /// - parameter fraction: Fraction of input color. From 0.0 to 1.0. 0.0 means solid color, 1.0 means transparent overlay.
  454. ///
  455. /// - returns: An image with a color overlay applied.
  456. ///
  457. /// - Note: This method only works for CG-based image.
  458. public func overlaying(with color: Color, fraction: CGFloat) -> Image {
  459. guard let cgImage = cgImage else {
  460. assertionFailure("[Kingfisher] Overlaying only works for CG-based image.")
  461. return base
  462. }
  463. let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
  464. return draw(cgImage: cgImage, to: rect.size) {
  465. #if os(macOS)
  466. base.draw(in: rect)
  467. if fraction > 0 {
  468. color.withAlphaComponent(1 - fraction).set()
  469. NSRectFillUsingOperation(rect, .sourceAtop)
  470. }
  471. #else
  472. color.set()
  473. UIRectFill(rect)
  474. base.draw(in: rect, blendMode: .destinationIn, alpha: 1.0)
  475. if fraction > 0 {
  476. base.draw(in: rect, blendMode: .sourceAtop, alpha: fraction)
  477. }
  478. #endif
  479. }
  480. }
  481. // MARK: - Tint
  482. /// Create an image from `self` with a color tint.
  483. ///
  484. /// - parameter color: The color should be used to tint `self`
  485. ///
  486. /// - returns: An image with a color tint applied.
  487. public func tinted(with color: Color) -> Image {
  488. #if os(watchOS)
  489. return base
  490. #else
  491. return apply(.tint(color))
  492. #endif
  493. }
  494. // MARK: - Color Control
  495. /// Create an image from `self` with color control.
  496. ///
  497. /// - parameter brightness: Brightness changing to image.
  498. /// - parameter contrast: Contrast changing to image.
  499. /// - parameter saturation: Saturation changing to image.
  500. /// - parameter inputEV: InputEV changing to image.
  501. ///
  502. /// - returns: An image with color control applied.
  503. public func adjusted(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) -> Image {
  504. #if os(watchOS)
  505. return base
  506. #else
  507. return apply(.colorControl(brightness, contrast, saturation, inputEV))
  508. #endif
  509. }
  510. }
  511. // MARK: - Decode
  512. extension Kingfisher where Base: Image {
  513. var decoded: Image? {
  514. return decoded(scale: scale)
  515. }
  516. func decoded(scale: CGFloat) -> Image {
  517. // prevent animated image (GIF) lose it's images
  518. #if os(iOS)
  519. if imageSource != nil { return base }
  520. #else
  521. if images != nil { return base }
  522. #endif
  523. guard let imageRef = self.cgImage else {
  524. assertionFailure("[Kingfisher] Decoding only works for CG-based image.")
  525. return base
  526. }
  527. let colorSpace = CGColorSpaceCreateDeviceRGB()
  528. let bitmapInfo = imageRef.bitmapInfo.fixed
  529. guard let context = CGContext(data: nil, width: imageRef.width, height: imageRef.height, bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: bitmapInfo.rawValue) else {
  530. assertionFailure("[Kingfisher] Decoding fails to create a valid context.")
  531. return base
  532. }
  533. let rect = CGRect(x: 0, y: 0, width: imageRef.width, height: imageRef.height)
  534. context.draw(imageRef, in: rect)
  535. let decompressedImageRef = context.makeImage()
  536. return Kingfisher<Image>.image(cgImage: decompressedImageRef!, scale: scale, refImage: base)
  537. }
  538. }
  539. /// Reference the source image reference
  540. class ImageSource {
  541. var imageRef: CGImageSource?
  542. init(ref: CGImageSource) {
  543. self.imageRef = ref
  544. }
  545. }
  546. // MARK: - Image format
  547. private struct ImageHeaderData {
  548. static var PNG: [UInt8] = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]
  549. static var JPEG_SOI: [UInt8] = [0xFF, 0xD8]
  550. static var JPEG_IF: [UInt8] = [0xFF]
  551. static var GIF: [UInt8] = [0x47, 0x49, 0x46]
  552. }
  553. enum ImageFormat {
  554. case unknown, PNG, JPEG, GIF
  555. }
  556. // MARK: - Misc Helpers
  557. public struct DataProxy {
  558. fileprivate let base: Data
  559. init(proxy: Data) {
  560. base = proxy
  561. }
  562. }
  563. extension Data: KingfisherCompatible {
  564. public typealias CompatibleType = DataProxy
  565. public var kf: DataProxy {
  566. return DataProxy(proxy: self)
  567. }
  568. }
  569. extension DataProxy {
  570. var imageFormat: ImageFormat {
  571. var buffer = [UInt8](repeating: 0, count: 8)
  572. (base as NSData).getBytes(&buffer, length: 8)
  573. if buffer == ImageHeaderData.PNG {
  574. return .PNG
  575. } else if buffer[0] == ImageHeaderData.JPEG_SOI[0] &&
  576. buffer[1] == ImageHeaderData.JPEG_SOI[1] &&
  577. buffer[2] == ImageHeaderData.JPEG_IF[0]
  578. {
  579. return .JPEG
  580. } else if buffer[0] == ImageHeaderData.GIF[0] &&
  581. buffer[1] == ImageHeaderData.GIF[1] &&
  582. buffer[2] == ImageHeaderData.GIF[2]
  583. {
  584. return .GIF
  585. }
  586. return .unknown
  587. }
  588. }
  589. public struct CGSizeProxy {
  590. fileprivate let base: CGSize
  591. init(proxy: CGSize) {
  592. base = proxy
  593. }
  594. }
  595. extension CGSize: KingfisherCompatible {
  596. public typealias CompatibleType = CGSizeProxy
  597. public var kf: CGSizeProxy {
  598. return CGSizeProxy(proxy: self)
  599. }
  600. }
  601. extension CGSizeProxy {
  602. func constrained(_ size: CGSize) -> CGSize {
  603. let aspectWidth = round(aspectRatio * size.height)
  604. let aspectHeight = round(size.width / aspectRatio)
  605. return aspectWidth > size.width ? CGSize(width: size.width, height: aspectHeight) : CGSize(width: aspectWidth, height: size.height)
  606. }
  607. func filling(_ size: CGSize) -> CGSize {
  608. let aspectWidth = round(aspectRatio * size.height)
  609. let aspectHeight = round(size.width / aspectRatio)
  610. return aspectWidth < size.width ? CGSize(width: size.width, height: aspectHeight) : CGSize(width: aspectWidth, height: size.height)
  611. }
  612. private var aspectRatio: CGFloat {
  613. return base.height == 0.0 ? 1.0 : base.width / base.height
  614. }
  615. }
  616. extension CGBitmapInfo {
  617. var fixed: CGBitmapInfo {
  618. var fixed = self
  619. let alpha = (rawValue & CGBitmapInfo.alphaInfoMask.rawValue)
  620. if alpha == CGImageAlphaInfo.none.rawValue {
  621. fixed.remove(.alphaInfoMask)
  622. fixed = CGBitmapInfo(rawValue: fixed.rawValue | CGImageAlphaInfo.noneSkipFirst.rawValue)
  623. } else if !(alpha == CGImageAlphaInfo.noneSkipFirst.rawValue) || !(alpha == CGImageAlphaInfo.noneSkipLast.rawValue) {
  624. fixed.remove(.alphaInfoMask)
  625. fixed = CGBitmapInfo(rawValue: fixed.rawValue | CGImageAlphaInfo.premultipliedFirst.rawValue)
  626. }
  627. return fixed
  628. }
  629. }
  630. extension Kingfisher where Base: Image {
  631. func draw(cgImage: CGImage?, to size: CGSize, draw: ()->()) -> Image {
  632. #if os(macOS)
  633. guard let rep = NSBitmapImageRep(
  634. bitmapDataPlanes: nil,
  635. pixelsWide: Int(size.width),
  636. pixelsHigh: Int(size.height),
  637. bitsPerSample: cgImage?.bitsPerComponent ?? 8,
  638. samplesPerPixel: 4,
  639. hasAlpha: true,
  640. isPlanar: false,
  641. colorSpaceName: NSCalibratedRGBColorSpace,
  642. bytesPerRow: 0,
  643. bitsPerPixel: 0) else
  644. {
  645. assertionFailure("[Kingfisher] Image representation cannot be created.")
  646. return base
  647. }
  648. rep.size = size
  649. NSGraphicsContext.saveGraphicsState()
  650. let context = NSGraphicsContext(bitmapImageRep: rep)
  651. NSGraphicsContext.setCurrent(context)
  652. draw()
  653. NSGraphicsContext.restoreGraphicsState()
  654. let outputImage = Image(size: size)
  655. outputImage.addRepresentation(rep)
  656. return outputImage
  657. #else
  658. UIGraphicsBeginImageContextWithOptions(size, false, scale)
  659. defer { UIGraphicsEndImageContext() }
  660. draw()
  661. return UIGraphicsGetImageFromCurrentImageContext() ?? base
  662. #endif
  663. }
  664. #if os(macOS)
  665. func fixedForRetinaPixel(cgImage: CGImage, to size: CGSize) -> Image {
  666. let image = Image(cgImage: cgImage, size: base.size)
  667. let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
  668. return draw(cgImage: cgImage, to: self.size) {
  669. image.draw(in: rect, from: NSRect.zero, operation: .copy, fraction: 1.0)
  670. }
  671. }
  672. #endif
  673. }
  674. extension CGContext {
  675. static func createARGBContext(from imageRef: CGImage) -> CGContext? {
  676. let w = imageRef.width
  677. let h = imageRef.height
  678. let bytesPerRow = w * 4
  679. let colorSpace = CGColorSpaceCreateDeviceRGB()
  680. let data = malloc(bytesPerRow * h)
  681. defer {
  682. free(data)
  683. }
  684. let bitmapInfo = imageRef.bitmapInfo.fixed
  685. // Create the bitmap context. We want pre-multiplied ARGB, 8-bits
  686. // per component. Regardless of what the source image format is
  687. // (CMYK, Grayscale, and so on) it will be converted over to the format
  688. // specified here.
  689. return CGContext(data: data,
  690. width: w,
  691. height: h,
  692. bitsPerComponent: imageRef.bitsPerComponent,
  693. bytesPerRow: bytesPerRow,
  694. space: colorSpace,
  695. bitmapInfo: bitmapInfo.rawValue)
  696. }
  697. }
  698. extension Double {
  699. var isEven: Bool {
  700. return truncatingRemainder(dividingBy: 2.0) == 0
  701. }
  702. }
  703. // MARK: - Deprecated. Only for back compatibility.
  704. extension Image {
  705. /**
  706. Normalize the image. This method does nothing in OS X.
  707. - returns: The image itself.
  708. */
  709. @available(*, deprecated,
  710. message: "Extensions directly on Image are deprecated. Use `kf.normalized` instead.",
  711. renamed: "kf.normalized")
  712. public func kf_normalized() -> Image {
  713. return kf.normalized
  714. }
  715. // MARK: - Round Corner
  716. /// Create a round corner image based on `self`.
  717. ///
  718. /// - parameter radius: The round corner radius of creating image.
  719. /// - parameter size: The target size of creating image.
  720. /// - parameter scale: The image scale of creating image.
  721. ///
  722. /// - returns: An image with round corner of `self`.
  723. ///
  724. /// - Note: This method only works for CG-based image.
  725. @available(*, deprecated,
  726. message: "Extensions directly on Image are deprecated. Use `kf.image(withRoundRadius:fit:scale:)` instead.",
  727. renamed: "kf.image")
  728. public func kf_image(withRoundRadius radius: CGFloat, fit size: CGSize, scale: CGFloat) -> Image {
  729. return kf.image(withRoundRadius: radius, fit: size)
  730. }
  731. // MARK: - Resize
  732. /// Resize `self` to an image of new size.
  733. ///
  734. /// - parameter size: The target size.
  735. ///
  736. /// - returns: An image with new size.
  737. ///
  738. /// - Note: This method only works for CG-based image.
  739. @available(*, deprecated,
  740. message: "Extensions directly on Image are deprecated. Use `kf.resize(to:)` instead.",
  741. renamed: "kf.resize")
  742. public func kf_resize(to size: CGSize) -> Image {
  743. return kf.resize(to: size)
  744. }
  745. // MARK: - Blur
  746. /// Create an image with blur effect based on `self`.
  747. ///
  748. /// - parameter radius: The blur radius should be used when creating blue.
  749. ///
  750. /// - returns: An image with blur effect applied.
  751. ///
  752. /// - Note: This method only works for CG-based image.
  753. @available(*, deprecated,
  754. message: "Extensions directly on Image are deprecated. Use `kf.blurred(withRadius:)` instead.",
  755. renamed: "kf.blurred")
  756. public func kf_blurred(withRadius radius: CGFloat) -> Image {
  757. return kf.blurred(withRadius: radius)
  758. }
  759. // MARK: - Overlay
  760. /// Create an image from `self` with a color overlay layer.
  761. ///
  762. /// - parameter color: The color should be use to overlay.
  763. /// - parameter fraction: Fraction of input color. From 0.0 to 1.0. 0.0 means solid color, 1.0 means transparent overlay.
  764. ///
  765. /// - returns: An image with a color overlay applied.
  766. ///
  767. /// - Note: This method only works for CG-based image.
  768. @available(*, deprecated,
  769. message: "Extensions directly on Image are deprecated. Use `kf.overlaying(with:fraction:)` instead.",
  770. renamed: "kf.overlaying")
  771. public func kf_overlaying(with color: Color, fraction: CGFloat) -> Image {
  772. return kf.overlaying(with: color, fraction: fraction)
  773. }
  774. // MARK: - Tint
  775. /// Create an image from `self` with a color tint.
  776. ///
  777. /// - parameter color: The color should be used to tint `self`
  778. ///
  779. /// - returns: An image with a color tint applied.
  780. @available(*, deprecated,
  781. message: "Extensions directly on Image are deprecated. Use `kf.tinted(with:)` instead.",
  782. renamed: "kf.tinted")
  783. public func kf_tinted(with color: Color) -> Image {
  784. return kf.tinted(with: color)
  785. }
  786. // MARK: - Color Control
  787. /// Create an image from `self` with color control.
  788. ///
  789. /// - parameter brightness: Brightness changing to image.
  790. /// - parameter contrast: Contrast changing to image.
  791. /// - parameter saturation: Saturation changing to image.
  792. /// - parameter inputEV: InputEV changing to image.
  793. ///
  794. /// - returns: An image with color control applied.
  795. @available(*, deprecated,
  796. message: "Extensions directly on Image are deprecated. Use `kf.adjusted` instead.",
  797. renamed: "kf.adjusted")
  798. public func kf_adjusted(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) -> Image {
  799. return kf.adjusted(brightness: brightness, contrast: contrast, saturation: saturation, inputEV: inputEV)
  800. }
  801. }
  802. extension Kingfisher where Base: Image {
  803. @available(*, deprecated,
  804. message: "`scale` is not used. Use the version without scale instead. (Remove the `scale` argument)")
  805. public func image(withRoundRadius radius: CGFloat, fit size: CGSize, scale: CGFloat) -> Image {
  806. return image(withRoundRadius: radius, fit: size)
  807. }
  808. }