Image.swift 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975
  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. #endif
  35. private var animatedImageDataKey: Void?
  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. fileprivate(set) var animatedImageData: Data? {
  45. get {
  46. return objc_getAssociatedObject(base, &animatedImageDataKey) as? Data
  47. }
  48. set {
  49. objc_setAssociatedObject(base, &animatedImageDataKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
  50. }
  51. }
  52. #if os(macOS)
  53. var cgImage: CGImage? {
  54. return base.cgImage(forProposedRect: nil, context: nil, hints: nil)
  55. }
  56. var scale: CGFloat {
  57. return 1.0
  58. }
  59. fileprivate(set) var images: [Image]? {
  60. get {
  61. return objc_getAssociatedObject(base, &imagesKey) as? [Image]
  62. }
  63. set {
  64. objc_setAssociatedObject(base, &imagesKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
  65. }
  66. }
  67. fileprivate(set) var duration: TimeInterval {
  68. get {
  69. return objc_getAssociatedObject(base, &durationKey) as? TimeInterval ?? 0.0
  70. }
  71. set {
  72. objc_setAssociatedObject(base, &durationKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
  73. }
  74. }
  75. var size: CGSize {
  76. return base.representations.reduce(CGSize.zero, { size, rep in
  77. return CGSize(width: max(size.width, CGFloat(rep.pixelsWide)), height: max(size.height, CGFloat(rep.pixelsHigh)))
  78. })
  79. }
  80. #else
  81. var cgImage: CGImage? {
  82. return base.cgImage
  83. }
  84. var scale: CGFloat {
  85. return base.scale
  86. }
  87. var images: [Image]? {
  88. return base.images
  89. }
  90. var duration: TimeInterval {
  91. return base.duration
  92. }
  93. fileprivate(set) var imageSource: ImageSource? {
  94. get {
  95. return objc_getAssociatedObject(base, &imageSourceKey) as? ImageSource
  96. }
  97. set {
  98. objc_setAssociatedObject(base, &imageSourceKey, 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. return animatedImageData
  177. }
  178. }
  179. // MARK: - Create images from data
  180. extension Kingfisher where Base: Image {
  181. static func animated(with data: Data, scale: CGFloat = 1.0, duration: TimeInterval = 0.0, preloadAll: Bool, onlyFirstFrame: Bool = false) -> Image? {
  182. func decode(from imageSource: CGImageSource, for options: NSDictionary) -> ([Image], TimeInterval)? {
  183. //Calculates frame duration for a gif frame out of the kCGImagePropertyGIFDictionary dictionary
  184. func frameDuration(from gifInfo: NSDictionary?) -> Double {
  185. let gifDefaultFrameDuration = 0.100
  186. guard let gifInfo = gifInfo else {
  187. return gifDefaultFrameDuration
  188. }
  189. let unclampedDelayTime = gifInfo[kCGImagePropertyGIFUnclampedDelayTime as String] as? NSNumber
  190. let delayTime = gifInfo[kCGImagePropertyGIFDelayTime as String] as? NSNumber
  191. let duration = unclampedDelayTime ?? delayTime
  192. guard let frameDuration = duration else { return gifDefaultFrameDuration }
  193. return frameDuration.doubleValue > 0.011 ? frameDuration.doubleValue : gifDefaultFrameDuration
  194. }
  195. let frameCount = CGImageSourceGetCount(imageSource)
  196. var images = [Image]()
  197. var gifDuration = 0.0
  198. for i in 0 ..< frameCount {
  199. guard let imageRef = CGImageSourceCreateImageAtIndex(imageSource, i, options) else {
  200. return nil
  201. }
  202. if frameCount == 1 {
  203. // Single frame
  204. gifDuration = Double.infinity
  205. } else {
  206. // Animated GIF
  207. guard let properties = CGImageSourceCopyPropertiesAtIndex(imageSource, i, nil) else {
  208. return nil
  209. }
  210. let gifInfo = (properties as NSDictionary)[kCGImagePropertyGIFDictionary as String] as? NSDictionary
  211. gifDuration += frameDuration(from: gifInfo)
  212. }
  213. images.append(Kingfisher<Image>.image(cgImage: imageRef, scale: scale, refImage: nil))
  214. if onlyFirstFrame { break }
  215. }
  216. return (images, gifDuration)
  217. }
  218. // Start of kf.animatedImageWithGIFData
  219. let options: NSDictionary = [kCGImageSourceShouldCache as String: true, kCGImageSourceTypeIdentifierHint as String: kUTTypeGIF]
  220. guard let imageSource = CGImageSourceCreateWithData(data as CFData, options) else {
  221. return nil
  222. }
  223. #if os(macOS)
  224. guard let (images, gifDuration) = decode(from: imageSource, for: options) else {
  225. return nil
  226. }
  227. let image: Image?
  228. if onlyFirstFrame {
  229. image = images.first
  230. } else {
  231. image = Image(data: data)
  232. image?.kf.images = images
  233. image?.kf.duration = gifDuration
  234. }
  235. image?.kf.animatedImageData = data
  236. return image
  237. #else
  238. let image: Image?
  239. if preloadAll || onlyFirstFrame {
  240. guard let (images, gifDuration) = decode(from: imageSource, for: options) else { return nil }
  241. image = onlyFirstFrame ? images.first : Kingfisher<Image>.animated(with: images, forDuration: duration <= 0.0 ? gifDuration : duration)
  242. } else {
  243. image = Image(data: data)
  244. image?.kf.imageSource = ImageSource(ref: imageSource)
  245. }
  246. image?.kf.animatedImageData = data
  247. return image
  248. #endif
  249. }
  250. static func image(data: Data, scale: CGFloat, preloadAllGIFData: Bool, onlyFirstFrame: Bool) -> Image? {
  251. var image: Image?
  252. #if os(macOS)
  253. switch data.kf.imageFormat {
  254. case .JPEG:
  255. image = Image(data: data)
  256. case .PNG:
  257. image = Image(data: data)
  258. case .GIF:
  259. image = Kingfisher<Image>.animated(
  260. with: data,
  261. scale: scale,
  262. duration: 0.0,
  263. preloadAll: preloadAllGIFData,
  264. onlyFirstFrame: onlyFirstFrame)
  265. case .unknown:
  266. image = Image(data: data)
  267. }
  268. #else
  269. switch data.kf.imageFormat {
  270. case .JPEG:
  271. image = Image(data: data, scale: scale)
  272. case .PNG:
  273. image = Image(data: data, scale: scale)
  274. case .GIF:
  275. image = Kingfisher<Image>.animated(
  276. with: data,
  277. scale: scale,
  278. duration: 0.0,
  279. preloadAll: preloadAllGIFData,
  280. onlyFirstFrame: onlyFirstFrame)
  281. case .unknown:
  282. 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 corner 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. return resize(to: size, for: .aspectFit)
  328. case .scaleAspectFill:
  329. return resize(to: size, for: .aspectFill)
  330. default:
  331. return resize(to: size)
  332. }
  333. }
  334. #endif
  335. // MARK: - Resize
  336. /// Resize `self` to an image of new size.
  337. ///
  338. /// - parameter size: The target size.
  339. ///
  340. /// - returns: An image with new size.
  341. ///
  342. /// - Note: This method only works for CG-based image.
  343. public func resize(to size: CGSize) -> Image {
  344. guard let cgImage = cgImage else {
  345. assertionFailure("[Kingfisher] Resize only works for CG-based image.")
  346. return base
  347. }
  348. let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
  349. return draw(cgImage: cgImage, to: size) {
  350. #if os(macOS)
  351. base.draw(in: rect, from: NSRect.zero, operation: .copy, fraction: 1.0)
  352. #else
  353. base.draw(in: rect)
  354. #endif
  355. }
  356. }
  357. /// Resize `self` to an image of new size, respecting the content mode.
  358. ///
  359. /// - Parameters:
  360. /// - size: The target size.
  361. /// - contentMode: Content mode of output image should be.
  362. /// - Returns: An image with new size.
  363. public func resize(to size: CGSize, for contentMode: ContentMode) -> Image {
  364. switch contentMode {
  365. case .aspectFit:
  366. let newSize = self.size.kf.constrained(size)
  367. return resize(to: newSize)
  368. case .aspectFill:
  369. let newSize = self.size.kf.filling(size)
  370. return resize(to: newSize)
  371. default:
  372. return resize(to: size)
  373. }
  374. }
  375. public func crop(to size: CGSize, anchorOn anchor: CGPoint) -> Image {
  376. guard let cgImage = cgImage else {
  377. assertionFailure("[Kingfisher] Crop only works for CG-based image.")
  378. return base
  379. }
  380. let rect = self.size.kf.constrainedRect(for: size, anchor: anchor)
  381. guard let image = cgImage.cropping(to: rect) else {
  382. assertionFailure("[Kingfisher] Cropping image failed.")
  383. return base
  384. }
  385. return Kingfisher.image(cgImage: image, scale: scale, refImage: base)
  386. }
  387. // MARK: - Blur
  388. /// Create an image with blur effect based on `self`.
  389. ///
  390. /// - parameter radius: The blur radius should be used when creating blue.
  391. ///
  392. /// - returns: An image with blur effect applied.
  393. ///
  394. /// - Note: This method only works for CG-based image.
  395. public func blurred(withRadius radius: CGFloat) -> Image {
  396. #if os(watchOS)
  397. return base
  398. #else
  399. guard let cgImage = cgImage else {
  400. assertionFailure("[Kingfisher] Blur only works for CG-based image.")
  401. return base
  402. }
  403. // http://www.w3.org/TR/SVG/filters.html#feGaussianBlurElement
  404. // let d = floor(s * 3*sqrt(2*pi)/4 + 0.5)
  405. // if d is odd, use three box-blurs of size 'd', centered on the output pixel.
  406. let s = Float(max(radius, 2.0))
  407. // We will do blur on a resized image (*0.5), so the blur radius could be half as well.
  408. // Fix the slow compiling time for Swift 3.
  409. // See https://github.com/onevcat/Kingfisher/issues/611
  410. let pi2 = 2 * Float.pi
  411. let sqrtPi2 = sqrt(pi2)
  412. var targetRadius = floor(s * 3.0 * sqrtPi2 / 4.0 + 0.5)
  413. if targetRadius.isEven {
  414. targetRadius += 1
  415. }
  416. let iterations: Int
  417. if radius < 0.5 {
  418. iterations = 1
  419. } else if radius < 1.5 {
  420. iterations = 2
  421. } else {
  422. iterations = 3
  423. }
  424. let w = Int(size.width)
  425. let h = Int(size.height)
  426. let rowBytes = Int(CGFloat(cgImage.bytesPerRow))
  427. func createEffectBuffer(_ context: CGContext) -> vImage_Buffer {
  428. let data = context.data
  429. let width = vImagePixelCount(context.width)
  430. let height = vImagePixelCount(context.height)
  431. let rowBytes = context.bytesPerRow
  432. return vImage_Buffer(data: data, height: height, width: width, rowBytes: rowBytes)
  433. }
  434. guard let context = beginContext(size: size) else {
  435. assertionFailure("[Kingfisher] Failed to create CG context for blurring image.")
  436. return base
  437. }
  438. defer { endContext() }
  439. context.draw(cgImage, in: CGRect(x: 0, y: 0, width: w, height: h))
  440. var inBuffer = createEffectBuffer(context)
  441. guard let outContext = beginContext(size: size) else {
  442. assertionFailure("[Kingfisher] Failed to create CG context for blurring image.")
  443. return base
  444. }
  445. defer { endContext() }
  446. var outBuffer = createEffectBuffer(outContext)
  447. for _ in 0 ..< iterations {
  448. vImageBoxConvolve_ARGB8888(&inBuffer, &outBuffer, nil, 0, 0, UInt32(targetRadius), UInt32(targetRadius), nil, vImage_Flags(kvImageEdgeExtend))
  449. (inBuffer, outBuffer) = (outBuffer, inBuffer)
  450. }
  451. #if os(macOS)
  452. let result = outContext.makeImage().flatMap { fixedForRetinaPixel(cgImage: $0, to: size) }
  453. #else
  454. let result = outContext.makeImage().flatMap { Image(cgImage: $0, scale: base.scale, orientation: base.imageOrientation) }
  455. #endif
  456. guard let blurredImage = result else {
  457. assertionFailure("[Kingfisher] Can not make an blurred image within this context.")
  458. return base
  459. }
  460. return blurredImage
  461. #endif
  462. }
  463. // MARK: - Overlay
  464. /// Create an image from `self` with a color overlay layer.
  465. ///
  466. /// - parameter color: The color should be use to overlay.
  467. /// - parameter fraction: Fraction of input color. From 0.0 to 1.0. 0.0 means solid color, 1.0 means transparent overlay.
  468. ///
  469. /// - returns: An image with a color overlay applied.
  470. ///
  471. /// - Note: This method only works for CG-based image.
  472. public func overlaying(with color: Color, fraction: CGFloat) -> Image {
  473. guard let cgImage = cgImage else {
  474. assertionFailure("[Kingfisher] Overlaying only works for CG-based image.")
  475. return base
  476. }
  477. let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
  478. return draw(cgImage: cgImage, to: rect.size) {
  479. #if os(macOS)
  480. base.draw(in: rect)
  481. if fraction > 0 {
  482. color.withAlphaComponent(1 - fraction).set()
  483. NSRectFillUsingOperation(rect, .sourceAtop)
  484. }
  485. #else
  486. color.set()
  487. UIRectFill(rect)
  488. base.draw(in: rect, blendMode: .destinationIn, alpha: 1.0)
  489. if fraction > 0 {
  490. base.draw(in: rect, blendMode: .sourceAtop, alpha: fraction)
  491. }
  492. #endif
  493. }
  494. }
  495. // MARK: - Tint
  496. /// Create an image from `self` with a color tint.
  497. ///
  498. /// - parameter color: The color should be used to tint `self`
  499. ///
  500. /// - returns: An image with a color tint applied.
  501. public func tinted(with color: Color) -> Image {
  502. #if os(watchOS)
  503. return base
  504. #else
  505. return apply(.tint(color))
  506. #endif
  507. }
  508. // MARK: - Color Control
  509. /// Create an image from `self` with color control.
  510. ///
  511. /// - parameter brightness: Brightness changing to image.
  512. /// - parameter contrast: Contrast changing to image.
  513. /// - parameter saturation: Saturation changing to image.
  514. /// - parameter inputEV: InputEV changing to image.
  515. ///
  516. /// - returns: An image with color control applied.
  517. public func adjusted(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) -> Image {
  518. #if os(watchOS)
  519. return base
  520. #else
  521. return apply(.colorControl(brightness, contrast, saturation, inputEV))
  522. #endif
  523. }
  524. }
  525. // MARK: - Decode
  526. extension Kingfisher where Base: Image {
  527. var decoded: Image? {
  528. return decoded(scale: scale)
  529. }
  530. func decoded(scale: CGFloat) -> Image {
  531. // prevent animated image (GIF) lose it's images
  532. #if os(iOS)
  533. if imageSource != nil { return base }
  534. #else
  535. if images != nil { return base }
  536. #endif
  537. guard let imageRef = self.cgImage else {
  538. assertionFailure("[Kingfisher] Decoding only works for CG-based image.")
  539. return base
  540. }
  541. let colorSpace = CGColorSpaceCreateDeviceRGB()
  542. guard let context = beginContext(size: CGSize(width: imageRef.width, height: imageRef.height)) else {
  543. assertionFailure("[Kingfisher] Decoding fails to create a valid context.")
  544. return base
  545. }
  546. defer { endContext() }
  547. let rect = CGRect(x: 0, y: 0, width: imageRef.width, height: imageRef.height)
  548. context.draw(imageRef, in: rect)
  549. let decompressedImageRef = context.makeImage()
  550. return Kingfisher<Image>.image(cgImage: decompressedImageRef!, scale: scale, refImage: base)
  551. }
  552. }
  553. /// Reference the source image reference
  554. class ImageSource {
  555. var imageRef: CGImageSource?
  556. init(ref: CGImageSource) {
  557. self.imageRef = ref
  558. }
  559. }
  560. // MARK: - Image format
  561. private struct ImageHeaderData {
  562. static var PNG: [UInt8] = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]
  563. static var JPEG_SOI: [UInt8] = [0xFF, 0xD8]
  564. static var JPEG_IF: [UInt8] = [0xFF]
  565. static var GIF: [UInt8] = [0x47, 0x49, 0x46]
  566. }
  567. enum ImageFormat {
  568. case unknown, PNG, JPEG, GIF
  569. }
  570. // MARK: - Misc Helpers
  571. public struct DataProxy {
  572. fileprivate let base: Data
  573. init(proxy: Data) {
  574. base = proxy
  575. }
  576. }
  577. extension Data: KingfisherCompatible {
  578. public typealias CompatibleType = DataProxy
  579. public var kf: DataProxy {
  580. return DataProxy(proxy: self)
  581. }
  582. }
  583. extension DataProxy {
  584. var imageFormat: ImageFormat {
  585. var buffer = [UInt8](repeating: 0, count: 8)
  586. (base as NSData).getBytes(&buffer, length: 8)
  587. if buffer == ImageHeaderData.PNG {
  588. return .PNG
  589. } else if buffer[0] == ImageHeaderData.JPEG_SOI[0] &&
  590. buffer[1] == ImageHeaderData.JPEG_SOI[1] &&
  591. buffer[2] == ImageHeaderData.JPEG_IF[0]
  592. {
  593. return .JPEG
  594. } else if buffer[0] == ImageHeaderData.GIF[0] &&
  595. buffer[1] == ImageHeaderData.GIF[1] &&
  596. buffer[2] == ImageHeaderData.GIF[2]
  597. {
  598. return .GIF
  599. }
  600. return .unknown
  601. }
  602. }
  603. public struct CGSizeProxy {
  604. fileprivate let base: CGSize
  605. init(proxy: CGSize) {
  606. base = proxy
  607. }
  608. }
  609. extension CGSize: KingfisherCompatible {
  610. public typealias CompatibleType = CGSizeProxy
  611. public var kf: CGSizeProxy {
  612. return CGSizeProxy(proxy: self)
  613. }
  614. }
  615. extension CGSizeProxy {
  616. func constrained(_ size: CGSize) -> CGSize {
  617. let aspectWidth = round(aspectRatio * size.height)
  618. let aspectHeight = round(size.width / aspectRatio)
  619. return aspectWidth > size.width ? CGSize(width: size.width, height: aspectHeight) : CGSize(width: aspectWidth, height: size.height)
  620. }
  621. func filling(_ size: CGSize) -> CGSize {
  622. let aspectWidth = round(aspectRatio * size.height)
  623. let aspectHeight = round(size.width / aspectRatio)
  624. return aspectWidth < size.width ? CGSize(width: size.width, height: aspectHeight) : CGSize(width: aspectWidth, height: size.height)
  625. }
  626. private var aspectRatio: CGFloat {
  627. return base.height == 0.0 ? 1.0 : base.width / base.height
  628. }
  629. func constrainedRect(for size: CGSize, anchor: CGPoint) -> CGRect {
  630. let unifiedAnchor = CGPoint(x: anchor.x.clamped(to: 0.0...1.0),
  631. y: anchor.y.clamped(to: 0.0...1.0))
  632. let x = unifiedAnchor.x * base.width - unifiedAnchor.x * size.width
  633. let y = unifiedAnchor.y * base.height - unifiedAnchor.y * size.height
  634. let r = CGRect(x: x, y: y, width: size.width, height: size.height)
  635. let ori = CGRect(origin: CGPoint.zero, size: base)
  636. return ori.intersection(r)
  637. }
  638. }
  639. extension Comparable {
  640. func clamped(to limits: ClosedRange<Self>) -> Self {
  641. return min(max(self, limits.lowerBound), limits.upperBound)
  642. }
  643. }
  644. extension Kingfisher where Base: Image {
  645. func beginContext(size: CGSize) -> CGContext? {
  646. #if os(macOS)
  647. guard let rep = NSBitmapImageRep(
  648. bitmapDataPlanes: nil,
  649. pixelsWide: Int(size.width),
  650. pixelsHigh: Int(size.height),
  651. bitsPerSample: cgImage?.bitsPerComponent ?? 8,
  652. samplesPerPixel: 4,
  653. hasAlpha: true,
  654. isPlanar: false,
  655. colorSpaceName: NSCalibratedRGBColorSpace,
  656. bytesPerRow: 0,
  657. bitsPerPixel: 0) else
  658. {
  659. assertionFailure("[Kingfisher] Image representation cannot be created.")
  660. return nil
  661. }
  662. rep.size = size
  663. NSGraphicsContext.saveGraphicsState()
  664. guard let context = NSGraphicsContext(bitmapImageRep: rep) else {
  665. assertionFailure("[Kingfisher] Image contenxt cannot be created.")
  666. return nil
  667. }
  668. NSGraphicsContext.setCurrent(context)
  669. return context.cgContext
  670. #else
  671. UIGraphicsBeginImageContextWithOptions(size, false, scale)
  672. let context = UIGraphicsGetCurrentContext()
  673. context?.scaleBy(x: 1.0, y: -1.0)
  674. context?.translateBy(x: 0, y: -size.height)
  675. return context
  676. #endif
  677. }
  678. func endContext() {
  679. #if os(macOS)
  680. NSGraphicsContext.restoreGraphicsState()
  681. #else
  682. UIGraphicsEndImageContext()
  683. #endif
  684. }
  685. func draw(cgImage: CGImage?, to size: CGSize, draw: ()->()) -> Image {
  686. #if os(macOS)
  687. guard let rep = NSBitmapImageRep(
  688. bitmapDataPlanes: nil,
  689. pixelsWide: Int(size.width),
  690. pixelsHigh: Int(size.height),
  691. bitsPerSample: cgImage?.bitsPerComponent ?? 8,
  692. samplesPerPixel: 4,
  693. hasAlpha: true,
  694. isPlanar: false,
  695. colorSpaceName: NSCalibratedRGBColorSpace,
  696. bytesPerRow: 0,
  697. bitsPerPixel: 0) else
  698. {
  699. assertionFailure("[Kingfisher] Image representation cannot be created.")
  700. return base
  701. }
  702. rep.size = size
  703. NSGraphicsContext.saveGraphicsState()
  704. let context = NSGraphicsContext(bitmapImageRep: rep)
  705. NSGraphicsContext.setCurrent(context)
  706. draw()
  707. NSGraphicsContext.restoreGraphicsState()
  708. let outputImage = Image(size: size)
  709. outputImage.addRepresentation(rep)
  710. return outputImage
  711. #else
  712. UIGraphicsBeginImageContextWithOptions(size, false, scale)
  713. defer { UIGraphicsEndImageContext() }
  714. draw()
  715. return UIGraphicsGetImageFromCurrentImageContext() ?? base
  716. #endif
  717. }
  718. #if os(macOS)
  719. func fixedForRetinaPixel(cgImage: CGImage, to size: CGSize) -> Image {
  720. let image = Image(cgImage: cgImage, size: base.size)
  721. let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
  722. return draw(cgImage: cgImage, to: self.size) {
  723. image.draw(in: rect, from: NSRect.zero, operation: .copy, fraction: 1.0)
  724. }
  725. }
  726. #endif
  727. }
  728. extension Float {
  729. var isEven: Bool {
  730. return truncatingRemainder(dividingBy: 2.0) == 0
  731. }
  732. }
  733. // MARK: - Deprecated. Only for back compatibility.
  734. extension Image {
  735. /**
  736. Normalize the image. This method does nothing in OS X.
  737. - returns: The image itself.
  738. */
  739. @available(*, deprecated,
  740. message: "Extensions directly on Image are deprecated. Use `kf.normalized` instead.",
  741. renamed: "kf.normalized")
  742. public func kf_normalized() -> Image {
  743. return kf.normalized
  744. }
  745. // MARK: - Round Corner
  746. /// Create a round corner image based on `self`.
  747. ///
  748. /// - parameter radius: The round corner radius of creating image.
  749. /// - parameter size: The target size of creating image.
  750. /// - parameter scale: The image scale of creating image.
  751. ///
  752. /// - returns: An image with round corner of `self`.
  753. ///
  754. /// - Note: This method only works for CG-based image.
  755. @available(*, deprecated,
  756. message: "Extensions directly on Image are deprecated. Use `kf.image(withRoundRadius:fit:scale:)` instead.",
  757. renamed: "kf.image")
  758. public func kf_image(withRoundRadius radius: CGFloat, fit size: CGSize, scale: CGFloat) -> Image {
  759. return kf.image(withRoundRadius: radius, fit: size)
  760. }
  761. // MARK: - Resize
  762. /// Resize `self` to an image of new size.
  763. ///
  764. /// - parameter size: The target size.
  765. ///
  766. /// - returns: An image with new size.
  767. ///
  768. /// - Note: This method only works for CG-based image.
  769. @available(*, deprecated,
  770. message: "Extensions directly on Image are deprecated. Use `kf.resize(to:)` instead.",
  771. renamed: "kf.resize")
  772. public func kf_resize(to size: CGSize) -> Image {
  773. return kf.resize(to: size)
  774. }
  775. // MARK: - Blur
  776. /// Create an image with blur effect based on `self`.
  777. ///
  778. /// - parameter radius: The blur radius should be used when creating blue.
  779. ///
  780. /// - returns: An image with blur effect applied.
  781. ///
  782. /// - Note: This method only works for CG-based image.
  783. @available(*, deprecated,
  784. message: "Extensions directly on Image are deprecated. Use `kf.blurred(withRadius:)` instead.",
  785. renamed: "kf.blurred")
  786. public func kf_blurred(withRadius radius: CGFloat) -> Image {
  787. return kf.blurred(withRadius: radius)
  788. }
  789. // MARK: - Overlay
  790. /// Create an image from `self` with a color overlay layer.
  791. ///
  792. /// - parameter color: The color should be use to overlay.
  793. /// - parameter fraction: Fraction of input color. From 0.0 to 1.0. 0.0 means solid color, 1.0 means transparent overlay.
  794. ///
  795. /// - returns: An image with a color overlay applied.
  796. ///
  797. /// - Note: This method only works for CG-based image.
  798. @available(*, deprecated,
  799. message: "Extensions directly on Image are deprecated. Use `kf.overlaying(with:fraction:)` instead.",
  800. renamed: "kf.overlaying")
  801. public func kf_overlaying(with color: Color, fraction: CGFloat) -> Image {
  802. return kf.overlaying(with: color, fraction: fraction)
  803. }
  804. // MARK: - Tint
  805. /// Create an image from `self` with a color tint.
  806. ///
  807. /// - parameter color: The color should be used to tint `self`
  808. ///
  809. /// - returns: An image with a color tint applied.
  810. @available(*, deprecated,
  811. message: "Extensions directly on Image are deprecated. Use `kf.tinted(with:)` instead.",
  812. renamed: "kf.tinted")
  813. public func kf_tinted(with color: Color) -> Image {
  814. return kf.tinted(with: color)
  815. }
  816. // MARK: - Color Control
  817. /// Create an image from `self` with color control.
  818. ///
  819. /// - parameter brightness: Brightness changing to image.
  820. /// - parameter contrast: Contrast changing to image.
  821. /// - parameter saturation: Saturation changing to image.
  822. /// - parameter inputEV: InputEV changing to image.
  823. ///
  824. /// - returns: An image with color control applied.
  825. @available(*, deprecated,
  826. message: "Extensions directly on Image are deprecated. Use `kf.adjusted` instead.",
  827. renamed: "kf.adjusted")
  828. public func kf_adjusted(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) -> Image {
  829. return kf.adjusted(brightness: brightness, contrast: contrast, saturation: saturation, inputEV: inputEV)
  830. }
  831. }
  832. extension Kingfisher where Base: Image {
  833. @available(*, deprecated,
  834. message: "`scale` is not used. Use the version without scale instead. (Remove the `scale` argument)")
  835. public func image(withRoundRadius radius: CGFloat, fit size: CGSize, scale: CGFloat) -> Image {
  836. return image(withRoundRadius: radius, fit: size)
  837. }
  838. }