Image.swift 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925
  1. //
  2. // Image.swift
  3. // Kingfisher
  4. //
  5. // Created by Wei Wang on 16/1/6.
  6. //
  7. // Copyright (c) 2017 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. func createEffectBuffer(_ context: CGContext) -> vImage_Buffer {
  396. let data = context.data
  397. let width = vImagePixelCount(context.width)
  398. let height = vImagePixelCount(context.height)
  399. let rowBytes = context.bytesPerRow
  400. return vImage_Buffer(data: data, height: height, width: width, rowBytes: rowBytes)
  401. }
  402. guard let context = beginContext() else {
  403. assertionFailure("[Kingfisher] Failed to create CG context for blurring image.")
  404. return base
  405. }
  406. defer { endContext() }
  407. #if !os(macOS)
  408. context.scaleBy(x: 1.0, y: -1.0)
  409. context.translateBy(x: 0, y: -size.height)
  410. #endif
  411. context.draw(cgImage, in: CGRect(x: 0, y: 0, width: w, height: h))
  412. var inBuffer = createEffectBuffer(context)
  413. guard let outContext = beginContext() else {
  414. assertionFailure("[Kingfisher] Failed to create CG context for blurring image.")
  415. return base
  416. }
  417. defer { endContext() }
  418. var outBuffer = createEffectBuffer(outContext)
  419. for _ in 0 ..< iterations {
  420. vImageBoxConvolve_ARGB8888(&inBuffer, &outBuffer, nil, 0, 0, UInt32(targetRadius), UInt32(targetRadius), nil, vImage_Flags(kvImageEdgeExtend))
  421. (inBuffer, outBuffer) = (outBuffer, inBuffer)
  422. }
  423. #if os(macOS)
  424. let result = outContext.makeImage().flatMap { fixedForRetinaPixel(cgImage: $0, to: size) }
  425. #else
  426. let result = outContext.makeImage().flatMap { Image(cgImage: $0, scale: base.scale, orientation: base.imageOrientation) }
  427. #endif
  428. guard let blurredImage = result else {
  429. assertionFailure("[Kingfisher] Can not make an blurred image within this context.")
  430. return base
  431. }
  432. return blurredImage
  433. #endif
  434. }
  435. // MARK: - Overlay
  436. /// Create an image from `self` with a color overlay layer.
  437. ///
  438. /// - parameter color: The color should be use to overlay.
  439. /// - parameter fraction: Fraction of input color. From 0.0 to 1.0. 0.0 means solid color, 1.0 means transparent overlay.
  440. ///
  441. /// - returns: An image with a color overlay applied.
  442. ///
  443. /// - Note: This method only works for CG-based image.
  444. public func overlaying(with color: Color, fraction: CGFloat) -> Image {
  445. guard let cgImage = cgImage else {
  446. assertionFailure("[Kingfisher] Overlaying only works for CG-based image.")
  447. return base
  448. }
  449. let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
  450. return draw(cgImage: cgImage, to: rect.size) {
  451. #if os(macOS)
  452. base.draw(in: rect)
  453. if fraction > 0 {
  454. color.withAlphaComponent(1 - fraction).set()
  455. NSRectFillUsingOperation(rect, .sourceAtop)
  456. }
  457. #else
  458. color.set()
  459. UIRectFill(rect)
  460. base.draw(in: rect, blendMode: .destinationIn, alpha: 1.0)
  461. if fraction > 0 {
  462. base.draw(in: rect, blendMode: .sourceAtop, alpha: fraction)
  463. }
  464. #endif
  465. }
  466. }
  467. // MARK: - Tint
  468. /// Create an image from `self` with a color tint.
  469. ///
  470. /// - parameter color: The color should be used to tint `self`
  471. ///
  472. /// - returns: An image with a color tint applied.
  473. public func tinted(with color: Color) -> Image {
  474. #if os(watchOS)
  475. return base
  476. #else
  477. return apply(.tint(color))
  478. #endif
  479. }
  480. // MARK: - Color Control
  481. /// Create an image from `self` with color control.
  482. ///
  483. /// - parameter brightness: Brightness changing to image.
  484. /// - parameter contrast: Contrast changing to image.
  485. /// - parameter saturation: Saturation changing to image.
  486. /// - parameter inputEV: InputEV changing to image.
  487. ///
  488. /// - returns: An image with color control applied.
  489. public func adjusted(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) -> Image {
  490. #if os(watchOS)
  491. return base
  492. #else
  493. return apply(.colorControl(brightness, contrast, saturation, inputEV))
  494. #endif
  495. }
  496. }
  497. // MARK: - Decode
  498. extension Kingfisher where Base: Image {
  499. var decoded: Image? {
  500. return decoded(scale: scale)
  501. }
  502. func decoded(scale: CGFloat) -> Image {
  503. // prevent animated image (GIF) lose it's images
  504. #if os(iOS)
  505. if imageSource != nil { return base }
  506. #else
  507. if images != nil { return base }
  508. #endif
  509. guard let imageRef = self.cgImage else {
  510. assertionFailure("[Kingfisher] Decoding only works for CG-based image.")
  511. return base
  512. }
  513. let colorSpace = CGColorSpaceCreateDeviceRGB()
  514. guard let context = beginContext() else {
  515. assertionFailure("[Kingfisher] Decoding fails to create a valid context.")
  516. return base
  517. }
  518. defer { endContext() }
  519. let rect = CGRect(x: 0, y: 0, width: imageRef.width, height: imageRef.height)
  520. context.draw(imageRef, in: rect)
  521. let decompressedImageRef = context.makeImage()
  522. return Kingfisher<Image>.image(cgImage: decompressedImageRef!, scale: scale, refImage: base)
  523. }
  524. }
  525. /// Reference the source image reference
  526. class ImageSource {
  527. var imageRef: CGImageSource?
  528. init(ref: CGImageSource) {
  529. self.imageRef = ref
  530. }
  531. }
  532. // MARK: - Image format
  533. private struct ImageHeaderData {
  534. static var PNG: [UInt8] = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]
  535. static var JPEG_SOI: [UInt8] = [0xFF, 0xD8]
  536. static var JPEG_IF: [UInt8] = [0xFF]
  537. static var GIF: [UInt8] = [0x47, 0x49, 0x46]
  538. }
  539. enum ImageFormat {
  540. case unknown, PNG, JPEG, GIF
  541. }
  542. // MARK: - Misc Helpers
  543. public struct DataProxy {
  544. fileprivate let base: Data
  545. init(proxy: Data) {
  546. base = proxy
  547. }
  548. }
  549. extension Data: KingfisherCompatible {
  550. public typealias CompatibleType = DataProxy
  551. public var kf: DataProxy {
  552. return DataProxy(proxy: self)
  553. }
  554. }
  555. extension DataProxy {
  556. var imageFormat: ImageFormat {
  557. var buffer = [UInt8](repeating: 0, count: 8)
  558. (base as NSData).getBytes(&buffer, length: 8)
  559. if buffer == ImageHeaderData.PNG {
  560. return .PNG
  561. } else if buffer[0] == ImageHeaderData.JPEG_SOI[0] &&
  562. buffer[1] == ImageHeaderData.JPEG_SOI[1] &&
  563. buffer[2] == ImageHeaderData.JPEG_IF[0]
  564. {
  565. return .JPEG
  566. } else if buffer[0] == ImageHeaderData.GIF[0] &&
  567. buffer[1] == ImageHeaderData.GIF[1] &&
  568. buffer[2] == ImageHeaderData.GIF[2]
  569. {
  570. return .GIF
  571. }
  572. return .unknown
  573. }
  574. }
  575. public struct CGSizeProxy {
  576. fileprivate let base: CGSize
  577. init(proxy: CGSize) {
  578. base = proxy
  579. }
  580. }
  581. extension CGSize: KingfisherCompatible {
  582. public typealias CompatibleType = CGSizeProxy
  583. public var kf: CGSizeProxy {
  584. return CGSizeProxy(proxy: self)
  585. }
  586. }
  587. extension CGSizeProxy {
  588. func constrained(_ size: CGSize) -> CGSize {
  589. let aspectWidth = round(aspectRatio * size.height)
  590. let aspectHeight = round(size.width / aspectRatio)
  591. return aspectWidth > size.width ? CGSize(width: size.width, height: aspectHeight) : CGSize(width: aspectWidth, height: size.height)
  592. }
  593. func filling(_ size: CGSize) -> CGSize {
  594. let aspectWidth = round(aspectRatio * size.height)
  595. let aspectHeight = round(size.width / aspectRatio)
  596. return aspectWidth < size.width ? CGSize(width: size.width, height: aspectHeight) : CGSize(width: aspectWidth, height: size.height)
  597. }
  598. private var aspectRatio: CGFloat {
  599. return base.height == 0.0 ? 1.0 : base.width / base.height
  600. }
  601. }
  602. extension Kingfisher where Base: Image {
  603. func beginContext() -> CGContext? {
  604. #if os(macOS)
  605. guard let rep = NSBitmapImageRep(
  606. bitmapDataPlanes: nil,
  607. pixelsWide: Int(size.width),
  608. pixelsHigh: Int(size.height),
  609. bitsPerSample: cgImage?.bitsPerComponent ?? 8,
  610. samplesPerPixel: 4,
  611. hasAlpha: true,
  612. isPlanar: false,
  613. colorSpaceName: NSCalibratedRGBColorSpace,
  614. bytesPerRow: 0,
  615. bitsPerPixel: 0) else
  616. {
  617. assertionFailure("[Kingfisher] Image representation cannot be created.")
  618. return nil
  619. }
  620. rep.size = size
  621. NSGraphicsContext.saveGraphicsState()
  622. guard let context = NSGraphicsContext(bitmapImageRep: rep) else {
  623. assertionFailure("[Kingfisher] Image contenxt cannot be created.")
  624. return nil
  625. }
  626. NSGraphicsContext.setCurrent(context)
  627. return context.cgContext
  628. #else
  629. UIGraphicsBeginImageContextWithOptions(size, false, scale)
  630. return UIGraphicsGetCurrentContext()
  631. #endif
  632. }
  633. func endContext() {
  634. #if os(macOS)
  635. NSGraphicsContext.restoreGraphicsState()
  636. #else
  637. UIGraphicsEndImageContext()
  638. #endif
  639. }
  640. func draw(cgImage: CGImage?, to size: CGSize, draw: ()->()) -> Image {
  641. #if os(macOS)
  642. guard let rep = NSBitmapImageRep(
  643. bitmapDataPlanes: nil,
  644. pixelsWide: Int(size.width),
  645. pixelsHigh: Int(size.height),
  646. bitsPerSample: cgImage?.bitsPerComponent ?? 8,
  647. samplesPerPixel: 4,
  648. hasAlpha: true,
  649. isPlanar: false,
  650. colorSpaceName: NSCalibratedRGBColorSpace,
  651. bytesPerRow: 0,
  652. bitsPerPixel: 0) else
  653. {
  654. assertionFailure("[Kingfisher] Image representation cannot be created.")
  655. return base
  656. }
  657. rep.size = size
  658. NSGraphicsContext.saveGraphicsState()
  659. let context = NSGraphicsContext(bitmapImageRep: rep)
  660. NSGraphicsContext.setCurrent(context)
  661. draw()
  662. NSGraphicsContext.restoreGraphicsState()
  663. let outputImage = Image(size: size)
  664. outputImage.addRepresentation(rep)
  665. return outputImage
  666. #else
  667. UIGraphicsBeginImageContextWithOptions(size, false, scale)
  668. defer { UIGraphicsEndImageContext() }
  669. draw()
  670. return UIGraphicsGetImageFromCurrentImageContext() ?? base
  671. #endif
  672. }
  673. #if os(macOS)
  674. func fixedForRetinaPixel(cgImage: CGImage, to size: CGSize) -> Image {
  675. let image = Image(cgImage: cgImage, size: base.size)
  676. let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
  677. return draw(cgImage: cgImage, to: self.size) {
  678. image.draw(in: rect, from: NSRect.zero, operation: .copy, fraction: 1.0)
  679. }
  680. }
  681. #endif
  682. }
  683. extension Double {
  684. var isEven: Bool {
  685. return truncatingRemainder(dividingBy: 2.0) == 0
  686. }
  687. }
  688. // MARK: - Deprecated. Only for back compatibility.
  689. extension Image {
  690. /**
  691. Normalize the image. This method does nothing in OS X.
  692. - returns: The image itself.
  693. */
  694. @available(*, deprecated,
  695. message: "Extensions directly on Image are deprecated. Use `kf.normalized` instead.",
  696. renamed: "kf.normalized")
  697. public func kf_normalized() -> Image {
  698. return kf.normalized
  699. }
  700. // MARK: - Round Corner
  701. /// Create a round corner image based on `self`.
  702. ///
  703. /// - parameter radius: The round corner radius of creating image.
  704. /// - parameter size: The target size of creating image.
  705. /// - parameter scale: The image scale of creating image.
  706. ///
  707. /// - returns: An image with round corner of `self`.
  708. ///
  709. /// - Note: This method only works for CG-based image.
  710. @available(*, deprecated,
  711. message: "Extensions directly on Image are deprecated. Use `kf.image(withRoundRadius:fit:scale:)` instead.",
  712. renamed: "kf.image")
  713. public func kf_image(withRoundRadius radius: CGFloat, fit size: CGSize, scale: CGFloat) -> Image {
  714. return kf.image(withRoundRadius: radius, fit: size)
  715. }
  716. // MARK: - Resize
  717. /// Resize `self` to an image of new size.
  718. ///
  719. /// - parameter size: The target size.
  720. ///
  721. /// - returns: An image with new size.
  722. ///
  723. /// - Note: This method only works for CG-based image.
  724. @available(*, deprecated,
  725. message: "Extensions directly on Image are deprecated. Use `kf.resize(to:)` instead.",
  726. renamed: "kf.resize")
  727. public func kf_resize(to size: CGSize) -> Image {
  728. return kf.resize(to: size)
  729. }
  730. // MARK: - Blur
  731. /// Create an image with blur effect based on `self`.
  732. ///
  733. /// - parameter radius: The blur radius should be used when creating blue.
  734. ///
  735. /// - returns: An image with blur effect applied.
  736. ///
  737. /// - Note: This method only works for CG-based image.
  738. @available(*, deprecated,
  739. message: "Extensions directly on Image are deprecated. Use `kf.blurred(withRadius:)` instead.",
  740. renamed: "kf.blurred")
  741. public func kf_blurred(withRadius radius: CGFloat) -> Image {
  742. return kf.blurred(withRadius: radius)
  743. }
  744. // MARK: - Overlay
  745. /// Create an image from `self` with a color overlay layer.
  746. ///
  747. /// - parameter color: The color should be use to overlay.
  748. /// - parameter fraction: Fraction of input color. From 0.0 to 1.0. 0.0 means solid color, 1.0 means transparent overlay.
  749. ///
  750. /// - returns: An image with a color overlay 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.overlaying(with:fraction:)` instead.",
  755. renamed: "kf.overlaying")
  756. public func kf_overlaying(with color: Color, fraction: CGFloat) -> Image {
  757. return kf.overlaying(with: color, fraction: fraction)
  758. }
  759. // MARK: - Tint
  760. /// Create an image from `self` with a color tint.
  761. ///
  762. /// - parameter color: The color should be used to tint `self`
  763. ///
  764. /// - returns: An image with a color tint applied.
  765. @available(*, deprecated,
  766. message: "Extensions directly on Image are deprecated. Use `kf.tinted(with:)` instead.",
  767. renamed: "kf.tinted")
  768. public func kf_tinted(with color: Color) -> Image {
  769. return kf.tinted(with: color)
  770. }
  771. // MARK: - Color Control
  772. /// Create an image from `self` with color control.
  773. ///
  774. /// - parameter brightness: Brightness changing to image.
  775. /// - parameter contrast: Contrast changing to image.
  776. /// - parameter saturation: Saturation changing to image.
  777. /// - parameter inputEV: InputEV changing to image.
  778. ///
  779. /// - returns: An image with color control applied.
  780. @available(*, deprecated,
  781. message: "Extensions directly on Image are deprecated. Use `kf.adjusted` instead.",
  782. renamed: "kf.adjusted")
  783. public func kf_adjusted(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) -> Image {
  784. return kf.adjusted(brightness: brightness, contrast: contrast, saturation: saturation, inputEV: inputEV)
  785. }
  786. }
  787. extension Kingfisher where Base: Image {
  788. @available(*, deprecated,
  789. message: "`scale` is not used. Use the version without scale instead. (Remove the `scale` argument)")
  790. public func image(withRoundRadius radius: CGFloat, fit size: CGSize, scale: CGFloat) -> Image {
  791. return image(withRoundRadius: radius, fit: size)
  792. }
  793. }