Image.swift 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914
  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. let unclampedDelayTime = gifInfo[kCGImagePropertyGIFUnclampedDelayTime as String] as? NSNumber
  187. let delayTime = gifInfo[kCGImagePropertyGIFDelayTime as String] as? NSNumber
  188. let duration = unclampedDelayTime ?? delayTime
  189. guard let frameDuration = duration else { return gifDefaultFrameDuration }
  190. return frameDuration.doubleValue > 0.011 ? frameDuration.doubleValue : gifDefaultFrameDuration
  191. }
  192. let frameCount = CGImageSourceGetCount(imageSource)
  193. var images = [Image]()
  194. var gifDuration = 0.0
  195. for i in 0 ..< frameCount {
  196. guard let imageRef = CGImageSourceCreateImageAtIndex(imageSource, i, options) else {
  197. return nil
  198. }
  199. if frameCount == 1 {
  200. // Single frame
  201. gifDuration = Double.infinity
  202. } else {
  203. // Animated GIF
  204. guard let properties = CGImageSourceCopyPropertiesAtIndex(imageSource, i, nil),
  205. let gifInfo = (properties as NSDictionary)[kCGImagePropertyGIFDictionary as String] as? NSDictionary else
  206. {
  207. return nil
  208. }
  209. gifDuration += frameDuration(from: gifInfo)
  210. }
  211. images.append(Kingfisher<Image>.image(cgImage: imageRef, scale: scale, refImage: nil))
  212. if onlyFirstFrame { break }
  213. }
  214. return (images, gifDuration)
  215. }
  216. // Start of kf.animatedImageWithGIFData
  217. let options: NSDictionary = [kCGImageSourceShouldCache as String: true, kCGImageSourceTypeIdentifierHint as String: kUTTypeGIF]
  218. guard let imageSource = CGImageSourceCreateWithData(data as CFData, options) else {
  219. return nil
  220. }
  221. #if os(macOS)
  222. guard let (images, gifDuration) = decode(from: imageSource, for: options) else {
  223. return nil
  224. }
  225. let image: Image?
  226. if onlyFirstFrame {
  227. image = images.first
  228. } else {
  229. image = Image(data: data)
  230. image?.kf.images = images
  231. image?.kf.duration = gifDuration
  232. }
  233. image?.kf.animatedImageData = data
  234. return image
  235. #else
  236. let image: Image?
  237. if preloadAll || onlyFirstFrame {
  238. guard let (images, gifDuration) = decode(from: imageSource, for: options) else { return nil }
  239. image = onlyFirstFrame ? images.first : Kingfisher<Image>.animated(with: images, forDuration: duration <= 0.0 ? gifDuration : duration)
  240. } else {
  241. image = Image(data: data)
  242. image?.kf.imageSource = ImageSource(ref: imageSource)
  243. }
  244. image?.kf.animatedImageData = data
  245. return image
  246. #endif
  247. }
  248. static func image(data: Data, scale: CGFloat, preloadAllGIFData: Bool, onlyFirstFrame: Bool) -> Image? {
  249. var image: Image?
  250. #if os(macOS)
  251. switch data.kf.imageFormat {
  252. case .JPEG:
  253. image = Image(data: data)
  254. case .PNG:
  255. image = Image(data: data)
  256. case .GIF:
  257. image = Kingfisher<Image>.animated(
  258. with: data,
  259. scale: scale,
  260. duration: 0.0,
  261. preloadAll: preloadAllGIFData,
  262. onlyFirstFrame: onlyFirstFrame)
  263. case .unknown:
  264. image = Image(data: data)
  265. }
  266. #else
  267. switch data.kf.imageFormat {
  268. case .JPEG:
  269. image = Image(data: data, scale: scale)
  270. case .PNG:
  271. image = Image(data: data, scale: scale)
  272. case .GIF:
  273. image = Kingfisher<Image>.animated(
  274. with: data,
  275. scale: scale,
  276. duration: 0.0,
  277. preloadAll: preloadAllGIFData,
  278. onlyFirstFrame: onlyFirstFrame)
  279. case .unknown:
  280. image = Image(data: data, scale: scale)
  281. }
  282. #endif
  283. return image
  284. }
  285. }
  286. // MARK: - Image Transforming
  287. extension Kingfisher where Base: Image {
  288. // MARK: - Round Corner
  289. /// Create a round corner image based on `self`.
  290. ///
  291. /// - parameter radius: The round corner radius of creating image.
  292. /// - parameter size: The target size of creating image.
  293. ///
  294. /// - returns: An image with round corner of `self`.
  295. ///
  296. /// - Note: This method only works for CG-based image.
  297. public func image(withRoundRadius radius: CGFloat, fit size: CGSize) -> Image {
  298. guard let cgImage = cgImage else {
  299. assertionFailure("[Kingfisher] Round corner image only works for CG-based image.")
  300. return base
  301. }
  302. let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
  303. return draw(cgImage: cgImage, to: size) {
  304. #if os(macOS)
  305. let path = NSBezierPath(roundedRect: rect, xRadius: radius, yRadius: radius)
  306. path.windingRule = .evenOddWindingRule
  307. path.addClip()
  308. base.draw(in: rect)
  309. #else
  310. guard let context = UIGraphicsGetCurrentContext() else {
  311. assertionFailure("[Kingfisher] Failed to create CG context for image.")
  312. return
  313. }
  314. let path = UIBezierPath(roundedRect: rect, byRoundingCorners: .allCorners, cornerRadii: CGSize(width: radius, height: radius)).cgPath
  315. context.addPath(path)
  316. context.clip()
  317. base.draw(in: rect)
  318. #endif
  319. }
  320. }
  321. #if os(iOS) || os(tvOS)
  322. func resize(to size: CGSize, for contentMode: UIViewContentMode) -> Image {
  323. switch contentMode {
  324. case .scaleAspectFit:
  325. let newSize = self.size.kf.constrained(size)
  326. return resize(to: newSize)
  327. case .scaleAspectFill:
  328. let newSize = self.size.kf.filling(size)
  329. return resize(to: newSize)
  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. // MARK: - Blur
  358. /// Create an image with blur effect based on `self`.
  359. ///
  360. /// - parameter radius: The blur radius should be used when creating blue.
  361. ///
  362. /// - returns: An image with blur effect applied.
  363. ///
  364. /// - Note: This method only works for CG-based image.
  365. public func blurred(withRadius radius: CGFloat) -> Image {
  366. #if os(watchOS)
  367. return base
  368. #else
  369. guard let cgImage = cgImage else {
  370. assertionFailure("[Kingfisher] Blur only works for CG-based image.")
  371. return base
  372. }
  373. // http://www.w3.org/TR/SVG/filters.html#feGaussianBlurElement
  374. // let d = floor(s * 3*sqrt(2*pi)/4 + 0.5)
  375. // if d is odd, use three box-blurs of size 'd', centered on the output pixel.
  376. let s = Float(max(radius, 2.0))
  377. // We will do blur on a resized image (*0.5), so the blur radius could be half as well.
  378. var targetRadius = floor(s * 3.0 * sqrt(2 * Float.pi) / 4.0 + 0.5)
  379. if targetRadius.isEven {
  380. targetRadius += 1
  381. }
  382. let iterations: Int
  383. if radius < 0.5 {
  384. iterations = 1
  385. } else if radius < 1.5 {
  386. iterations = 2
  387. } else {
  388. iterations = 3
  389. }
  390. let w = Int(size.width)
  391. let h = Int(size.height)
  392. let rowBytes = Int(CGFloat(cgImage.bytesPerRow))
  393. func createEffectBuffer(_ context: CGContext) -> vImage_Buffer {
  394. let data = context.data
  395. let width = vImagePixelCount(context.width)
  396. let height = vImagePixelCount(context.height)
  397. let rowBytes = context.bytesPerRow
  398. return vImage_Buffer(data: data, height: height, width: width, rowBytes: rowBytes)
  399. }
  400. guard let context = beginContext() else {
  401. assertionFailure("[Kingfisher] Failed to create CG context for blurring image.")
  402. return base
  403. }
  404. defer { endContext() }
  405. context.draw(cgImage, in: CGRect(x: 0, y: 0, width: w, height: h))
  406. var inBuffer = createEffectBuffer(context)
  407. guard let outContext = beginContext() else {
  408. assertionFailure("[Kingfisher] Failed to create CG context for blurring image.")
  409. return base
  410. }
  411. defer { endContext() }
  412. var outBuffer = createEffectBuffer(outContext)
  413. for _ in 0 ..< iterations {
  414. vImageBoxConvolve_ARGB8888(&inBuffer, &outBuffer, nil, 0, 0, UInt32(targetRadius), UInt32(targetRadius), nil, vImage_Flags(kvImageEdgeExtend))
  415. (inBuffer, outBuffer) = (outBuffer, inBuffer)
  416. }
  417. #if os(macOS)
  418. let result = outContext.makeImage().flatMap { fixedForRetinaPixel(cgImage: $0, to: size) }
  419. #else
  420. let result = outContext.makeImage().flatMap { Image(cgImage: $0, scale: base.scale, orientation: base.imageOrientation) }
  421. #endif
  422. guard let blurredImage = result else {
  423. assertionFailure("[Kingfisher] Can not make an blurred image within this context.")
  424. return base
  425. }
  426. return blurredImage
  427. #endif
  428. }
  429. // MARK: - Overlay
  430. /// Create an image from `self` with a color overlay layer.
  431. ///
  432. /// - parameter color: The color should be use to overlay.
  433. /// - parameter fraction: Fraction of input color. From 0.0 to 1.0. 0.0 means solid color, 1.0 means transparent overlay.
  434. ///
  435. /// - returns: An image with a color overlay applied.
  436. ///
  437. /// - Note: This method only works for CG-based image.
  438. public func overlaying(with color: Color, fraction: CGFloat) -> Image {
  439. guard let cgImage = cgImage else {
  440. assertionFailure("[Kingfisher] Overlaying only works for CG-based image.")
  441. return base
  442. }
  443. let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
  444. return draw(cgImage: cgImage, to: rect.size) {
  445. #if os(macOS)
  446. base.draw(in: rect)
  447. if fraction > 0 {
  448. color.withAlphaComponent(1 - fraction).set()
  449. NSRectFillUsingOperation(rect, .sourceAtop)
  450. }
  451. #else
  452. color.set()
  453. UIRectFill(rect)
  454. base.draw(in: rect, blendMode: .destinationIn, alpha: 1.0)
  455. if fraction > 0 {
  456. base.draw(in: rect, blendMode: .sourceAtop, alpha: fraction)
  457. }
  458. #endif
  459. }
  460. }
  461. // MARK: - Tint
  462. /// Create an image from `self` with a color tint.
  463. ///
  464. /// - parameter color: The color should be used to tint `self`
  465. ///
  466. /// - returns: An image with a color tint applied.
  467. public func tinted(with color: Color) -> Image {
  468. #if os(watchOS)
  469. return base
  470. #else
  471. return apply(.tint(color))
  472. #endif
  473. }
  474. // MARK: - Color Control
  475. /// Create an image from `self` with color control.
  476. ///
  477. /// - parameter brightness: Brightness changing to image.
  478. /// - parameter contrast: Contrast changing to image.
  479. /// - parameter saturation: Saturation changing to image.
  480. /// - parameter inputEV: InputEV changing to image.
  481. ///
  482. /// - returns: An image with color control applied.
  483. public func adjusted(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) -> Image {
  484. #if os(watchOS)
  485. return base
  486. #else
  487. return apply(.colorControl(brightness, contrast, saturation, inputEV))
  488. #endif
  489. }
  490. }
  491. // MARK: - Decode
  492. extension Kingfisher where Base: Image {
  493. var decoded: Image? {
  494. return decoded(scale: scale)
  495. }
  496. func decoded(scale: CGFloat) -> Image {
  497. // prevent animated image (GIF) lose it's images
  498. #if os(iOS)
  499. if imageSource != nil { return base }
  500. #else
  501. if images != nil { return base }
  502. #endif
  503. guard let imageRef = self.cgImage else {
  504. assertionFailure("[Kingfisher] Decoding only works for CG-based image.")
  505. return base
  506. }
  507. let colorSpace = CGColorSpaceCreateDeviceRGB()
  508. guard let context = beginContext() else {
  509. assertionFailure("[Kingfisher] Decoding fails to create a valid context.")
  510. return base
  511. }
  512. defer { endContext() }
  513. let rect = CGRect(x: 0, y: 0, width: imageRef.width, height: imageRef.height)
  514. context.draw(imageRef, in: rect)
  515. let decompressedImageRef = context.makeImage()
  516. return Kingfisher<Image>.image(cgImage: decompressedImageRef!, scale: scale, refImage: base)
  517. }
  518. }
  519. /// Reference the source image reference
  520. class ImageSource {
  521. var imageRef: CGImageSource?
  522. init(ref: CGImageSource) {
  523. self.imageRef = ref
  524. }
  525. }
  526. // MARK: - Image format
  527. private struct ImageHeaderData {
  528. static var PNG: [UInt8] = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]
  529. static var JPEG_SOI: [UInt8] = [0xFF, 0xD8]
  530. static var JPEG_IF: [UInt8] = [0xFF]
  531. static var GIF: [UInt8] = [0x47, 0x49, 0x46]
  532. }
  533. enum ImageFormat {
  534. case unknown, PNG, JPEG, GIF
  535. }
  536. // MARK: - Misc Helpers
  537. public struct DataProxy {
  538. fileprivate let base: Data
  539. init(proxy: Data) {
  540. base = proxy
  541. }
  542. }
  543. extension Data: KingfisherCompatible {
  544. public typealias CompatibleType = DataProxy
  545. public var kf: DataProxy {
  546. return DataProxy(proxy: self)
  547. }
  548. }
  549. extension DataProxy {
  550. var imageFormat: ImageFormat {
  551. var buffer = [UInt8](repeating: 0, count: 8)
  552. (base as NSData).getBytes(&buffer, length: 8)
  553. if buffer == ImageHeaderData.PNG {
  554. return .PNG
  555. } else if buffer[0] == ImageHeaderData.JPEG_SOI[0] &&
  556. buffer[1] == ImageHeaderData.JPEG_SOI[1] &&
  557. buffer[2] == ImageHeaderData.JPEG_IF[0]
  558. {
  559. return .JPEG
  560. } else if buffer[0] == ImageHeaderData.GIF[0] &&
  561. buffer[1] == ImageHeaderData.GIF[1] &&
  562. buffer[2] == ImageHeaderData.GIF[2]
  563. {
  564. return .GIF
  565. }
  566. return .unknown
  567. }
  568. }
  569. public struct CGSizeProxy {
  570. fileprivate let base: CGSize
  571. init(proxy: CGSize) {
  572. base = proxy
  573. }
  574. }
  575. extension CGSize: KingfisherCompatible {
  576. public typealias CompatibleType = CGSizeProxy
  577. public var kf: CGSizeProxy {
  578. return CGSizeProxy(proxy: self)
  579. }
  580. }
  581. extension CGSizeProxy {
  582. func constrained(_ size: CGSize) -> CGSize {
  583. let aspectWidth = round(aspectRatio * size.height)
  584. let aspectHeight = round(size.width / aspectRatio)
  585. return aspectWidth > size.width ? CGSize(width: size.width, height: aspectHeight) : CGSize(width: aspectWidth, height: size.height)
  586. }
  587. func filling(_ size: CGSize) -> CGSize {
  588. let aspectWidth = round(aspectRatio * size.height)
  589. let aspectHeight = round(size.width / aspectRatio)
  590. return aspectWidth < size.width ? CGSize(width: size.width, height: aspectHeight) : CGSize(width: aspectWidth, height: size.height)
  591. }
  592. private var aspectRatio: CGFloat {
  593. return base.height == 0.0 ? 1.0 : base.width / base.height
  594. }
  595. }
  596. extension Kingfisher where Base: Image {
  597. func beginContext() -> CGContext? {
  598. #if os(macOS)
  599. guard let rep = NSBitmapImageRep(
  600. bitmapDataPlanes: nil,
  601. pixelsWide: Int(size.width),
  602. pixelsHigh: Int(size.height),
  603. bitsPerSample: cgImage?.bitsPerComponent ?? 8,
  604. samplesPerPixel: 4,
  605. hasAlpha: true,
  606. isPlanar: false,
  607. colorSpaceName: NSCalibratedRGBColorSpace,
  608. bytesPerRow: 0,
  609. bitsPerPixel: 0) else
  610. {
  611. assertionFailure("[Kingfisher] Image representation cannot be created.")
  612. return nil
  613. }
  614. rep.size = size
  615. NSGraphicsContext.saveGraphicsState()
  616. guard let context = NSGraphicsContext(bitmapImageRep: rep) else {
  617. assertionFailure("[Kingfisher] Image contenxt cannot be created.")
  618. return nil
  619. }
  620. NSGraphicsContext.setCurrent(context)
  621. return context.cgContext
  622. #else
  623. UIGraphicsBeginImageContextWithOptions(size, false, scale)
  624. let context = UIGraphicsGetCurrentContext()
  625. context?.scaleBy(x: 1.0, y: -1.0)
  626. context?.translateBy(x: 0, y: -size.height)
  627. return context
  628. #endif
  629. }
  630. func endContext() {
  631. #if os(macOS)
  632. NSGraphicsContext.restoreGraphicsState()
  633. #else
  634. UIGraphicsEndImageContext()
  635. #endif
  636. }
  637. func draw(cgImage: CGImage?, to size: CGSize, draw: ()->()) -> Image {
  638. #if os(macOS)
  639. guard let rep = NSBitmapImageRep(
  640. bitmapDataPlanes: nil,
  641. pixelsWide: Int(size.width),
  642. pixelsHigh: Int(size.height),
  643. bitsPerSample: cgImage?.bitsPerComponent ?? 8,
  644. samplesPerPixel: 4,
  645. hasAlpha: true,
  646. isPlanar: false,
  647. colorSpaceName: NSCalibratedRGBColorSpace,
  648. bytesPerRow: 0,
  649. bitsPerPixel: 0) else
  650. {
  651. assertionFailure("[Kingfisher] Image representation cannot be created.")
  652. return base
  653. }
  654. rep.size = size
  655. NSGraphicsContext.saveGraphicsState()
  656. let context = NSGraphicsContext(bitmapImageRep: rep)
  657. NSGraphicsContext.setCurrent(context)
  658. draw()
  659. NSGraphicsContext.restoreGraphicsState()
  660. let outputImage = Image(size: size)
  661. outputImage.addRepresentation(rep)
  662. return outputImage
  663. #else
  664. UIGraphicsBeginImageContextWithOptions(size, false, scale)
  665. defer { UIGraphicsEndImageContext() }
  666. draw()
  667. return UIGraphicsGetImageFromCurrentImageContext() ?? base
  668. #endif
  669. }
  670. #if os(macOS)
  671. func fixedForRetinaPixel(cgImage: CGImage, to size: CGSize) -> Image {
  672. let image = Image(cgImage: cgImage, size: base.size)
  673. let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
  674. return draw(cgImage: cgImage, to: self.size) {
  675. image.draw(in: rect, from: NSRect.zero, operation: .copy, fraction: 1.0)
  676. }
  677. }
  678. #endif
  679. }
  680. extension Float {
  681. var isEven: Bool {
  682. return truncatingRemainder(dividingBy: 2.0) == 0
  683. }
  684. }
  685. // MARK: - Deprecated. Only for back compatibility.
  686. extension Image {
  687. /**
  688. Normalize the image. This method does nothing in OS X.
  689. - returns: The image itself.
  690. */
  691. @available(*, deprecated,
  692. message: "Extensions directly on Image are deprecated. Use `kf.normalized` instead.",
  693. renamed: "kf.normalized")
  694. public func kf_normalized() -> Image {
  695. return kf.normalized
  696. }
  697. // MARK: - Round Corner
  698. /// Create a round corner image based on `self`.
  699. ///
  700. /// - parameter radius: The round corner radius of creating image.
  701. /// - parameter size: The target size of creating image.
  702. /// - parameter scale: The image scale of creating image.
  703. ///
  704. /// - returns: An image with round corner of `self`.
  705. ///
  706. /// - Note: This method only works for CG-based image.
  707. @available(*, deprecated,
  708. message: "Extensions directly on Image are deprecated. Use `kf.image(withRoundRadius:fit:scale:)` instead.",
  709. renamed: "kf.image")
  710. public func kf_image(withRoundRadius radius: CGFloat, fit size: CGSize, scale: CGFloat) -> Image {
  711. return kf.image(withRoundRadius: radius, fit: size)
  712. }
  713. // MARK: - Resize
  714. /// Resize `self` to an image of new size.
  715. ///
  716. /// - parameter size: The target size.
  717. ///
  718. /// - returns: An image with new size.
  719. ///
  720. /// - Note: This method only works for CG-based image.
  721. @available(*, deprecated,
  722. message: "Extensions directly on Image are deprecated. Use `kf.resize(to:)` instead.",
  723. renamed: "kf.resize")
  724. public func kf_resize(to size: CGSize) -> Image {
  725. return kf.resize(to: size)
  726. }
  727. // MARK: - Blur
  728. /// Create an image with blur effect based on `self`.
  729. ///
  730. /// - parameter radius: The blur radius should be used when creating blue.
  731. ///
  732. /// - returns: An image with blur effect applied.
  733. ///
  734. /// - Note: This method only works for CG-based image.
  735. @available(*, deprecated,
  736. message: "Extensions directly on Image are deprecated. Use `kf.blurred(withRadius:)` instead.",
  737. renamed: "kf.blurred")
  738. public func kf_blurred(withRadius radius: CGFloat) -> Image {
  739. return kf.blurred(withRadius: radius)
  740. }
  741. // MARK: - Overlay
  742. /// Create an image from `self` with a color overlay layer.
  743. ///
  744. /// - parameter color: The color should be use to overlay.
  745. /// - parameter fraction: Fraction of input color. From 0.0 to 1.0. 0.0 means solid color, 1.0 means transparent overlay.
  746. ///
  747. /// - returns: An image with a color overlay applied.
  748. ///
  749. /// - Note: This method only works for CG-based image.
  750. @available(*, deprecated,
  751. message: "Extensions directly on Image are deprecated. Use `kf.overlaying(with:fraction:)` instead.",
  752. renamed: "kf.overlaying")
  753. public func kf_overlaying(with color: Color, fraction: CGFloat) -> Image {
  754. return kf.overlaying(with: color, fraction: fraction)
  755. }
  756. // MARK: - Tint
  757. /// Create an image from `self` with a color tint.
  758. ///
  759. /// - parameter color: The color should be used to tint `self`
  760. ///
  761. /// - returns: An image with a color tint applied.
  762. @available(*, deprecated,
  763. message: "Extensions directly on Image are deprecated. Use `kf.tinted(with:)` instead.",
  764. renamed: "kf.tinted")
  765. public func kf_tinted(with color: Color) -> Image {
  766. return kf.tinted(with: color)
  767. }
  768. // MARK: - Color Control
  769. /// Create an image from `self` with color control.
  770. ///
  771. /// - parameter brightness: Brightness changing to image.
  772. /// - parameter contrast: Contrast changing to image.
  773. /// - parameter saturation: Saturation changing to image.
  774. /// - parameter inputEV: InputEV changing to image.
  775. ///
  776. /// - returns: An image with color control applied.
  777. @available(*, deprecated,
  778. message: "Extensions directly on Image are deprecated. Use `kf.adjusted` instead.",
  779. renamed: "kf.adjusted")
  780. public func kf_adjusted(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) -> Image {
  781. return kf.adjusted(brightness: brightness, contrast: contrast, saturation: saturation, inputEV: inputEV)
  782. }
  783. }
  784. extension Kingfisher where Base: Image {
  785. @available(*, deprecated,
  786. message: "`scale` is not used. Use the version without scale instead. (Remove the `scale` argument)")
  787. public func image(withRoundRadius radius: CGFloat, fit size: CGSize, scale: CGFloat) -> Image {
  788. return image(withRoundRadius: radius, fit: size)
  789. }
  790. }