Image.swift 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021
  1. //
  2. // Image.swift
  3. // Kingfisher
  4. //
  5. // Created by Wei Wang on 16/1/6.
  6. //
  7. // Copyright (c) 2018 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: [.compressionFactor: 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, preloadAllAnimationData: 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: preloadAllAnimationData,
  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: preloadAllAnimationData,
  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: - Blend Mode
  291. /// Create image based on `self` and apply blend mode.
  292. ///
  293. /// - parameter blendMode: The blend mode of creating image.
  294. /// - parameter alpha: The alpha should be used for image.
  295. /// - parameter backgroundColor: The background color for the output image.
  296. ///
  297. /// - returns: An image with blend mode applied.
  298. ///
  299. /// - Note: This method only works for CG-based image.
  300. #if !os(macOS)
  301. public func image(withBlendMode blendMode: CGBlendMode,
  302. alpha: CGFloat = 1.0,
  303. backgroundColor: Color? = nil) -> Image
  304. {
  305. guard let cgImage = cgImage else {
  306. assertionFailure("[Kingfisher] Blend mode image only works for CG-based image.")
  307. return base
  308. }
  309. let rect = CGRect(origin: .zero, size: size)
  310. return draw(cgImage: cgImage, to: rect.size) {
  311. if let backgroundColor = backgroundColor {
  312. backgroundColor.setFill()
  313. UIRectFill(rect)
  314. }
  315. base.draw(in: rect, blendMode: blendMode, alpha: alpha)
  316. }
  317. }
  318. #endif
  319. // MARK: - Compositing Operation
  320. /// Create image based on `self` and apply compositing operation.
  321. ///
  322. /// - parameter compositingOperation: The compositing operation of creating image.
  323. /// - parameter alpha: The alpha should be used for image.
  324. /// - parameter backgroundColor: The background color for the output image.
  325. ///
  326. /// - returns: An image with compositing operation applied.
  327. ///
  328. /// - Note: This method only works for CG-based image.
  329. #if os(macOS)
  330. public func image(withCompositingOperation compositingOperation: NSCompositingOperation,
  331. alpha: CGFloat = 1.0,
  332. backgroundColor: Color? = nil) -> Image
  333. {
  334. guard let cgImage = cgImage else {
  335. assertionFailure("[Kingfisher] Compositing Operation image only works for CG-based image.")
  336. return base
  337. }
  338. let rect = CGRect(origin: .zero, size: size)
  339. return draw(cgImage: cgImage, to: rect.size) {
  340. if let backgroundColor = backgroundColor {
  341. backgroundColor.setFill()
  342. rect.fill()
  343. }
  344. base.draw(in: rect, from: NSRect.zero, operation: compositingOperation, fraction: alpha)
  345. }
  346. }
  347. #endif
  348. // MARK: - Round Corner
  349. /// Create a round corner image based on `self`.
  350. ///
  351. /// - parameter radius: The round corner radius of creating image.
  352. /// - parameter size: The target size of creating image.
  353. /// - parameter corners: The target corners which will be applied rounding.
  354. /// - parameter backgroundColor: The background color for the output image
  355. ///
  356. /// - returns: An image with round corner of `self`.
  357. ///
  358. /// - Note: This method only works for CG-based image.
  359. public func image(withRoundRadius radius: CGFloat,
  360. fit size: CGSize,
  361. roundingCorners corners: RectCorner = .all,
  362. backgroundColor: Color? = nil) -> Image
  363. {
  364. guard let cgImage = cgImage else {
  365. assertionFailure("[Kingfisher] Round corner image only works for CG-based image.")
  366. return base
  367. }
  368. let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
  369. return draw(cgImage: cgImage, to: size) {
  370. #if os(macOS)
  371. if let backgroundColor = backgroundColor {
  372. let rectPath = NSBezierPath(rect: rect)
  373. backgroundColor.setFill()
  374. rectPath.fill()
  375. }
  376. let path = NSBezierPath(roundedRect: rect, byRoundingCorners: corners, radius: radius)
  377. path.windingRule = .evenOddWindingRule
  378. path.addClip()
  379. base.draw(in: rect)
  380. #else
  381. guard let context = UIGraphicsGetCurrentContext() else {
  382. assertionFailure("[Kingfisher] Failed to create CG context for image.")
  383. return
  384. }
  385. if let backgroundColor = backgroundColor {
  386. let rectPath = UIBezierPath(rect: rect)
  387. backgroundColor.setFill()
  388. rectPath.fill()
  389. }
  390. let path = UIBezierPath(roundedRect: rect,
  391. byRoundingCorners: corners.uiRectCorner,
  392. cornerRadii: CGSize(width: radius, height: radius)).cgPath
  393. context.addPath(path)
  394. context.clip()
  395. base.draw(in: rect)
  396. #endif
  397. }
  398. }
  399. #if os(iOS) || os(tvOS)
  400. func resize(to size: CGSize, for contentMode: UIViewContentMode) -> Image {
  401. switch contentMode {
  402. case .scaleAspectFit:
  403. return resize(to: size, for: .aspectFit)
  404. case .scaleAspectFill:
  405. return resize(to: size, for: .aspectFill)
  406. default:
  407. return resize(to: size)
  408. }
  409. }
  410. #endif
  411. // MARK: - Resize
  412. /// Resize `self` to an image of new size.
  413. ///
  414. /// - parameter size: The target size.
  415. ///
  416. /// - returns: An image with new size.
  417. ///
  418. /// - Note: This method only works for CG-based image.
  419. public func resize(to size: CGSize) -> Image {
  420. guard let cgImage = cgImage else {
  421. assertionFailure("[Kingfisher] Resize only works for CG-based image.")
  422. return base
  423. }
  424. let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
  425. return draw(cgImage: cgImage, to: size) {
  426. #if os(macOS)
  427. base.draw(in: rect, from: NSRect.zero, operation: .copy, fraction: 1.0)
  428. #else
  429. base.draw(in: rect)
  430. #endif
  431. }
  432. }
  433. /// Resize `self` to an image of new size, respecting the content mode.
  434. ///
  435. /// - Parameters:
  436. /// - size: The target size.
  437. /// - contentMode: Content mode of output image should be.
  438. /// - Returns: An image with new size.
  439. public func resize(to size: CGSize, for contentMode: ContentMode) -> Image {
  440. switch contentMode {
  441. case .aspectFit:
  442. let newSize = self.size.kf.constrained(size)
  443. return resize(to: newSize)
  444. case .aspectFill:
  445. let newSize = self.size.kf.filling(size)
  446. return resize(to: newSize)
  447. default:
  448. return resize(to: size)
  449. }
  450. }
  451. public func crop(to size: CGSize, anchorOn anchor: CGPoint) -> Image {
  452. guard let cgImage = cgImage else {
  453. assertionFailure("[Kingfisher] Crop only works for CG-based image.")
  454. return base
  455. }
  456. let rect = self.size.kf.constrainedRect(for: size, anchor: anchor)
  457. guard let image = cgImage.cropping(to: rect.scaled(scale)) else {
  458. assertionFailure("[Kingfisher] Cropping image failed.")
  459. return base
  460. }
  461. return Kingfisher.image(cgImage: image, scale: scale, refImage: base)
  462. }
  463. // MARK: - Blur
  464. /// Create an image with blur effect based on `self`.
  465. ///
  466. /// - parameter radius: The blur radius should be used when creating blur effect.
  467. ///
  468. /// - returns: An image with blur effect applied.
  469. ///
  470. /// - Note: This method only works for CG-based image.
  471. public func blurred(withRadius radius: CGFloat) -> Image {
  472. #if os(watchOS)
  473. return base
  474. #else
  475. guard let cgImage = cgImage else {
  476. assertionFailure("[Kingfisher] Blur only works for CG-based image.")
  477. return base
  478. }
  479. // http://www.w3.org/TR/SVG/filters.html#feGaussianBlurElement
  480. // let d = floor(s * 3*sqrt(2*pi)/4 + 0.5)
  481. // if d is odd, use three box-blurs of size 'd', centered on the output pixel.
  482. let s = Float(max(radius, 2.0))
  483. // We will do blur on a resized image (*0.5), so the blur radius could be half as well.
  484. // Fix the slow compiling time for Swift 3.
  485. // See https://github.com/onevcat/Kingfisher/issues/611
  486. let pi2 = 2 * Float.pi
  487. let sqrtPi2 = sqrt(pi2)
  488. var targetRadius = floor(s * 3.0 * sqrtPi2 / 4.0 + 0.5)
  489. if targetRadius.isEven {
  490. targetRadius += 1
  491. }
  492. let iterations: Int
  493. if radius < 0.5 {
  494. iterations = 1
  495. } else if radius < 1.5 {
  496. iterations = 2
  497. } else {
  498. iterations = 3
  499. }
  500. let w = Int(size.width)
  501. let h = Int(size.height)
  502. let rowBytes = Int(CGFloat(cgImage.bytesPerRow))
  503. func createEffectBuffer(_ context: CGContext) -> vImage_Buffer {
  504. let data = context.data
  505. let width = vImagePixelCount(context.width)
  506. let height = vImagePixelCount(context.height)
  507. let rowBytes = context.bytesPerRow
  508. return vImage_Buffer(data: data, height: height, width: width, rowBytes: rowBytes)
  509. }
  510. guard let context = beginContext(size: size, scale: scale) else {
  511. assertionFailure("[Kingfisher] Failed to create CG context for blurring image.")
  512. return base
  513. }
  514. defer { endContext() }
  515. context.draw(cgImage, in: CGRect(x: 0, y: 0, width: w, height: h))
  516. var inBuffer = createEffectBuffer(context)
  517. guard let outContext = beginContext(size: size, scale: scale) else {
  518. assertionFailure("[Kingfisher] Failed to create CG context for blurring image.")
  519. return base
  520. }
  521. defer { endContext() }
  522. var outBuffer = createEffectBuffer(outContext)
  523. for _ in 0 ..< iterations {
  524. vImageBoxConvolve_ARGB8888(&inBuffer, &outBuffer, nil, 0, 0, UInt32(targetRadius), UInt32(targetRadius), nil, vImage_Flags(kvImageEdgeExtend))
  525. (inBuffer, outBuffer) = (outBuffer, inBuffer)
  526. }
  527. #if os(macOS)
  528. let result = outContext.makeImage().flatMap { fixedForRetinaPixel(cgImage: $0, to: size) }
  529. #else
  530. let result = outContext.makeImage().flatMap { Image(cgImage: $0, scale: base.scale, orientation: base.imageOrientation) }
  531. #endif
  532. guard let blurredImage = result else {
  533. assertionFailure("[Kingfisher] Can not make an blurred image within this context.")
  534. return base
  535. }
  536. return blurredImage
  537. #endif
  538. }
  539. // MARK: - Overlay
  540. /// Create an image from `self` with a color overlay layer.
  541. ///
  542. /// - parameter color: The color should be use to overlay.
  543. /// - parameter fraction: Fraction of input color. From 0.0 to 1.0. 0.0 means solid color, 1.0 means transparent overlay.
  544. ///
  545. /// - returns: An image with a color overlay applied.
  546. ///
  547. /// - Note: This method only works for CG-based image.
  548. public func overlaying(with color: Color, fraction: CGFloat) -> Image {
  549. guard let cgImage = cgImage else {
  550. assertionFailure("[Kingfisher] Overlaying only works for CG-based image.")
  551. return base
  552. }
  553. let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
  554. return draw(cgImage: cgImage, to: rect.size) {
  555. #if os(macOS)
  556. base.draw(in: rect)
  557. if fraction > 0 {
  558. color.withAlphaComponent(1 - fraction).set()
  559. rect.fill(using: .sourceAtop)
  560. }
  561. #else
  562. color.set()
  563. UIRectFill(rect)
  564. base.draw(in: rect, blendMode: .destinationIn, alpha: 1.0)
  565. if fraction > 0 {
  566. base.draw(in: rect, blendMode: .sourceAtop, alpha: fraction)
  567. }
  568. #endif
  569. }
  570. }
  571. // MARK: - Tint
  572. /// Create an image from `self` with a color tint.
  573. ///
  574. /// - parameter color: The color should be used to tint `self`
  575. ///
  576. /// - returns: An image with a color tint applied.
  577. public func tinted(with color: Color) -> Image {
  578. #if os(watchOS)
  579. return base
  580. #else
  581. return apply(.tint(color))
  582. #endif
  583. }
  584. // MARK: - Color Control
  585. /// Create an image from `self` with color control.
  586. ///
  587. /// - parameter brightness: Brightness changing to image.
  588. /// - parameter contrast: Contrast changing to image.
  589. /// - parameter saturation: Saturation changing to image.
  590. /// - parameter inputEV: InputEV changing to image.
  591. ///
  592. /// - returns: An image with color control applied.
  593. public func adjusted(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) -> Image {
  594. #if os(watchOS)
  595. return base
  596. #else
  597. return apply(.colorControl((brightness, contrast, saturation, inputEV)))
  598. #endif
  599. }
  600. /// Return an image with given scale.
  601. ///
  602. /// - Parameter scale: Target scale factor the new image should have.
  603. /// - Returns: The image with target scale. If the base image is already in the scale, `base` will be returned.
  604. public func scaled(to scale: CGFloat) -> Image {
  605. guard scale != self.scale else {
  606. return base
  607. }
  608. guard let cgImage = cgImage else {
  609. assertionFailure("[Kingfisher] Scaling only works for CG-based image.")
  610. return base
  611. }
  612. return Kingfisher.image(cgImage: cgImage, scale: scale, refImage: base)
  613. }
  614. }
  615. // MARK: - Decode
  616. extension Kingfisher where Base: Image {
  617. var decoded: Image {
  618. return decoded(scale: scale)
  619. }
  620. func decoded(scale: CGFloat) -> Image {
  621. // prevent animated image (GIF) lose it's images
  622. #if os(iOS)
  623. if imageSource != nil { return base }
  624. #else
  625. if images != nil { return base }
  626. #endif
  627. guard let imageRef = self.cgImage else {
  628. assertionFailure("[Kingfisher] Decoding only works for CG-based image.")
  629. return base
  630. }
  631. // Draw CGImage in a plain context with scale of 1.0.
  632. guard let context = beginContext(size: CGSize(width: imageRef.width, height: imageRef.height), scale: 1.0) else {
  633. assertionFailure("[Kingfisher] Decoding fails to create a valid context.")
  634. return base
  635. }
  636. defer { endContext() }
  637. let rect = CGRect(x: 0, y: 0, width: CGFloat(imageRef.width), height: CGFloat(imageRef.height))
  638. context.draw(imageRef, in: rect)
  639. let decompressedImageRef = context.makeImage()
  640. return Kingfisher<Image>.image(cgImage: decompressedImageRef!, scale: scale, refImage: base)
  641. }
  642. }
  643. /// Reference the source image reference
  644. final class ImageSource {
  645. var imageRef: CGImageSource?
  646. init(ref: CGImageSource) {
  647. self.imageRef = ref
  648. }
  649. }
  650. // MARK: - Image format
  651. private struct ImageHeaderData {
  652. static var PNG: [UInt8] = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]
  653. static var JPEG_SOI: [UInt8] = [0xFF, 0xD8]
  654. static var JPEG_IF: [UInt8] = [0xFF]
  655. static var GIF: [UInt8] = [0x47, 0x49, 0x46]
  656. }
  657. enum ImageFormat {
  658. case unknown, PNG, JPEG, GIF
  659. }
  660. // MARK: - Misc Helpers
  661. public struct DataProxy {
  662. fileprivate let base: Data
  663. init(proxy: Data) {
  664. base = proxy
  665. }
  666. }
  667. extension Data: KingfisherCompatible {
  668. public typealias CompatibleType = DataProxy
  669. public var kf: DataProxy {
  670. return DataProxy(proxy: self)
  671. }
  672. }
  673. extension DataProxy {
  674. var imageFormat: ImageFormat {
  675. var buffer = [UInt8](repeating: 0, count: 8)
  676. (base as NSData).getBytes(&buffer, length: 8)
  677. if buffer == ImageHeaderData.PNG {
  678. return .PNG
  679. } else if buffer[0] == ImageHeaderData.JPEG_SOI[0] &&
  680. buffer[1] == ImageHeaderData.JPEG_SOI[1] &&
  681. buffer[2] == ImageHeaderData.JPEG_IF[0]
  682. {
  683. return .JPEG
  684. } else if buffer[0] == ImageHeaderData.GIF[0] &&
  685. buffer[1] == ImageHeaderData.GIF[1] &&
  686. buffer[2] == ImageHeaderData.GIF[2]
  687. {
  688. return .GIF
  689. }
  690. return .unknown
  691. }
  692. }
  693. public struct CGSizeProxy {
  694. fileprivate let base: CGSize
  695. init(proxy: CGSize) {
  696. base = proxy
  697. }
  698. }
  699. extension CGSize: KingfisherCompatible {
  700. public typealias CompatibleType = CGSizeProxy
  701. public var kf: CGSizeProxy {
  702. return CGSizeProxy(proxy: self)
  703. }
  704. }
  705. extension CGSizeProxy {
  706. func constrained(_ size: CGSize) -> CGSize {
  707. let aspectWidth = round(aspectRatio * size.height)
  708. let aspectHeight = round(size.width / aspectRatio)
  709. return aspectWidth > size.width ? CGSize(width: size.width, height: aspectHeight) : CGSize(width: aspectWidth, height: size.height)
  710. }
  711. func filling(_ size: CGSize) -> CGSize {
  712. let aspectWidth = round(aspectRatio * size.height)
  713. let aspectHeight = round(size.width / aspectRatio)
  714. return aspectWidth < size.width ? CGSize(width: size.width, height: aspectHeight) : CGSize(width: aspectWidth, height: size.height)
  715. }
  716. private var aspectRatio: CGFloat {
  717. return base.height == 0.0 ? 1.0 : base.width / base.height
  718. }
  719. func constrainedRect(for size: CGSize, anchor: CGPoint) -> CGRect {
  720. let unifiedAnchor = CGPoint(x: anchor.x.clamped(to: 0.0...1.0),
  721. y: anchor.y.clamped(to: 0.0...1.0))
  722. let x = unifiedAnchor.x * base.width - unifiedAnchor.x * size.width
  723. let y = unifiedAnchor.y * base.height - unifiedAnchor.y * size.height
  724. let r = CGRect(x: x, y: y, width: size.width, height: size.height)
  725. let ori = CGRect(origin: CGPoint.zero, size: base)
  726. return ori.intersection(r)
  727. }
  728. }
  729. extension CGRect {
  730. func scaled(_ scale: CGFloat) -> CGRect {
  731. return CGRect(x: origin.x * scale, y: origin.y * scale,
  732. width: size.width * scale, height: size.height * scale)
  733. }
  734. }
  735. extension Comparable {
  736. func clamped(to limits: ClosedRange<Self>) -> Self {
  737. return min(max(self, limits.lowerBound), limits.upperBound)
  738. }
  739. }
  740. extension Kingfisher where Base: Image {
  741. func beginContext(size: CGSize, scale: CGFloat) -> CGContext? {
  742. #if os(macOS)
  743. guard let rep = NSBitmapImageRep(
  744. bitmapDataPlanes: nil,
  745. pixelsWide: Int(size.width),
  746. pixelsHigh: Int(size.height),
  747. bitsPerSample: cgImage?.bitsPerComponent ?? 8,
  748. samplesPerPixel: 4,
  749. hasAlpha: true,
  750. isPlanar: false,
  751. colorSpaceName: .calibratedRGB,
  752. bytesPerRow: 0,
  753. bitsPerPixel: 0) else
  754. {
  755. assertionFailure("[Kingfisher] Image representation cannot be created.")
  756. return nil
  757. }
  758. rep.size = size
  759. NSGraphicsContext.saveGraphicsState()
  760. guard let context = NSGraphicsContext(bitmapImageRep: rep) else {
  761. assertionFailure("[Kingfisher] Image contenxt cannot be created.")
  762. return nil
  763. }
  764. NSGraphicsContext.current = context
  765. return context.cgContext
  766. #else
  767. UIGraphicsBeginImageContextWithOptions(size, false, scale)
  768. let context = UIGraphicsGetCurrentContext()
  769. context?.scaleBy(x: 1.0, y: -1.0)
  770. context?.translateBy(x: 0, y: -size.height)
  771. return context
  772. #endif
  773. }
  774. func endContext() {
  775. #if os(macOS)
  776. NSGraphicsContext.restoreGraphicsState()
  777. #else
  778. UIGraphicsEndImageContext()
  779. #endif
  780. }
  781. func draw(cgImage: CGImage?, to size: CGSize, draw: ()->()) -> Image {
  782. #if os(macOS)
  783. guard let rep = NSBitmapImageRep(
  784. bitmapDataPlanes: nil,
  785. pixelsWide: Int(size.width),
  786. pixelsHigh: Int(size.height),
  787. bitsPerSample: cgImage?.bitsPerComponent ?? 8,
  788. samplesPerPixel: 4,
  789. hasAlpha: true,
  790. isPlanar: false,
  791. colorSpaceName: .calibratedRGB,
  792. bytesPerRow: 0,
  793. bitsPerPixel: 0) else
  794. {
  795. assertionFailure("[Kingfisher] Image representation cannot be created.")
  796. return base
  797. }
  798. rep.size = size
  799. NSGraphicsContext.saveGraphicsState()
  800. let context = NSGraphicsContext(bitmapImageRep: rep)
  801. NSGraphicsContext.current = context
  802. draw()
  803. NSGraphicsContext.restoreGraphicsState()
  804. let outputImage = Image(size: size)
  805. outputImage.addRepresentation(rep)
  806. return outputImage
  807. #else
  808. UIGraphicsBeginImageContextWithOptions(size, false, scale)
  809. defer { UIGraphicsEndImageContext() }
  810. draw()
  811. return UIGraphicsGetImageFromCurrentImageContext() ?? base
  812. #endif
  813. }
  814. #if os(macOS)
  815. func fixedForRetinaPixel(cgImage: CGImage, to size: CGSize) -> Image {
  816. let image = Image(cgImage: cgImage, size: base.size)
  817. let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
  818. return draw(cgImage: cgImage, to: self.size) {
  819. image.draw(in: rect, from: NSRect.zero, operation: .copy, fraction: 1.0)
  820. }
  821. }
  822. #endif
  823. }
  824. extension Float {
  825. var isEven: Bool {
  826. return truncatingRemainder(dividingBy: 2.0) == 0
  827. }
  828. }
  829. #if os(macOS)
  830. extension NSBezierPath {
  831. convenience init(roundedRect rect: NSRect, topLeftRadius: CGFloat, topRightRadius: CGFloat,
  832. bottomLeftRadius: CGFloat, bottomRightRadius: CGFloat)
  833. {
  834. self.init()
  835. let maxCorner = min(rect.width, rect.height) / 2
  836. let radiusTopLeft = min(maxCorner, max(0, topLeftRadius))
  837. let radiustopRight = min(maxCorner, max(0, topRightRadius))
  838. let radiusbottomLeft = min(maxCorner, max(0, bottomLeftRadius))
  839. let radiusbottomRight = min(maxCorner, max(0, bottomRightRadius))
  840. guard !NSIsEmptyRect(rect) else {
  841. return
  842. }
  843. let topLeft = NSMakePoint(NSMinX(rect), NSMaxY(rect));
  844. let topRight = NSMakePoint(NSMaxX(rect), NSMaxY(rect));
  845. let bottomRight = NSMakePoint(NSMaxX(rect), NSMinY(rect));
  846. move(to: NSMakePoint(NSMidX(rect), NSMaxY(rect)))
  847. appendArc(from: topLeft, to: rect.origin, radius: radiusTopLeft)
  848. appendArc(from: rect.origin, to: bottomRight, radius: radiusbottomLeft)
  849. appendArc(from: bottomRight, to: topRight, radius: radiusbottomRight)
  850. appendArc(from: topRight, to: topLeft, radius: radiustopRight)
  851. close()
  852. }
  853. convenience init(roundedRect rect: NSRect, byRoundingCorners corners: RectCorner, radius: CGFloat) {
  854. let radiusTopLeft = corners.contains(.topLeft) ? radius : 0
  855. let radiusTopRight = corners.contains(.topRight) ? radius : 0
  856. let radiusBottomLeft = corners.contains(.bottomLeft) ? radius : 0
  857. let radiusBottomRight = corners.contains(.bottomRight) ? radius : 0
  858. self.init(roundedRect: rect, topLeftRadius: radiusTopLeft, topRightRadius: radiusTopRight,
  859. bottomLeftRadius: radiusBottomLeft, bottomRightRadius: radiusBottomRight)
  860. }
  861. }
  862. #else
  863. extension RectCorner {
  864. var uiRectCorner: UIRectCorner {
  865. var result: UIRectCorner = []
  866. if self.contains(.topLeft) { result.insert(.topLeft) }
  867. if self.contains(.topRight) { result.insert(.topRight) }
  868. if self.contains(.bottomLeft) { result.insert(.bottomLeft) }
  869. if self.contains(.bottomRight) { result.insert(.bottomRight) }
  870. return result
  871. }
  872. }
  873. #endif