Image.swift 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  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. #if !os(watchOS)
  36. import CoreImage
  37. #endif
  38. import CoreGraphics
  39. import ImageIO
  40. private var animatedImageDataKey: Void?
  41. func getAssociatedObject<T>(_ object: Any, _ key: UnsafeRawPointer) -> T? {
  42. return objc_getAssociatedObject(object, key) as? T
  43. }
  44. func setRetainedAssociatedObject<T>(_ object: Any, _ key: UnsafeRawPointer, _ value: T) {
  45. objc_setAssociatedObject(object, key, value, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
  46. }
  47. // MARK: - Image Properties
  48. extension KingfisherClass where Base: Image {
  49. private(set) var animatedImageData: Data? {
  50. get { return getAssociatedObject(base, &animatedImageDataKey) }
  51. set { setRetainedAssociatedObject(base, &animatedImageDataKey, newValue) }
  52. }
  53. #if os(macOS)
  54. var cgImage: CGImage? {
  55. return base.cgImage(forProposedRect: nil, context: nil, hints: nil)
  56. }
  57. var scale: CGFloat {
  58. return 1.0
  59. }
  60. private(set) var images: [Image]? {
  61. get { return getAssociatedObject(base, &imagesKey) }
  62. set { setRetainedAssociatedObject(base, &imagesKey, newValue) }
  63. }
  64. private(set) var duration: TimeInterval {
  65. get { return getAssociatedObject(base, &durationKey) ?? 0.0 }
  66. set { setRetainedAssociatedObject(base, &durationKey, newValue) }
  67. }
  68. var size: CGSize {
  69. return base.representations.reduce(.zero) { size, rep in
  70. let width = max(size.width, CGFloat(rep.pixelsWide))
  71. let height = max(size.height, CGFloat(rep.pixelsHigh))
  72. return CGSize(width: width, height: height)
  73. }
  74. }
  75. #else
  76. var cgImage: CGImage? { return base.cgImage }
  77. var scale: CGFloat { return base.scale }
  78. var images: [Image]? { return base.images }
  79. var duration: TimeInterval { return base.duration }
  80. var size: CGSize { return base.size }
  81. private(set) var imageSource: CGImageSource? {
  82. get { return getAssociatedObject(base, &imageSourceKey) }
  83. set { setRetainedAssociatedObject(base, &imageSourceKey, newValue) }
  84. }
  85. #endif
  86. }
  87. // MARK: - Image Conversion
  88. extension KingfisherClass where Base: Image {
  89. #if os(macOS)
  90. static func image(cgImage: CGImage, scale: CGFloat, refImage: Image?) -> Image {
  91. return Image(cgImage: cgImage, size: .zero)
  92. }
  93. /// Normalize the image. This getter does nothing on macOS but return the image itself.
  94. public var normalized: Image { return base }
  95. #else
  96. /// Creating an image from a give `CGImage` at scale and orientation for refImage. The method signature is for
  97. /// compability of macOS version.
  98. static func image(cgImage: CGImage, scale: CGFloat, refImage: Image?) -> Image {
  99. return Image(cgImage: cgImage, scale: scale, orientation: refImage?.imageOrientation ?? .up)
  100. }
  101. /// Normalized image of current `base`.
  102. /// This method will try to redraw an image with orientation and scale considered.
  103. public var normalized: Image {
  104. // prevent animated image (GIF) lose it's images
  105. guard images == nil else { return base }
  106. // No need to do anything if already up
  107. guard base.imageOrientation != .up else { return base }
  108. return draw(to: size) {
  109. base.draw(in: CGRect(origin: .zero, size: size))
  110. }
  111. }
  112. #endif
  113. }
  114. // MARK: - Image Representation
  115. extension KingfisherClass where Base: Image {
  116. // MARK: - PNG
  117. /// Returns PNG representation of `base` image.
  118. ///
  119. /// - Returns: PNG data of image.
  120. public func pngRepresentation() -> Data? {
  121. #if os(macOS)
  122. guard let cgimage = cgImage else {
  123. return nil
  124. }
  125. let rep = NSBitmapImageRep(cgImage: cgimage)
  126. return rep.representation(using: .png, properties: [:])
  127. #else
  128. return base.pngData()
  129. #endif
  130. }
  131. // MARK: - JPEG
  132. /// Returns JPEG representation of `base` image.
  133. ///
  134. /// - Parameter compressionQuality: The compression quality when converting image to JPEG data.
  135. /// - Returns: JPEG data of image.
  136. public func jpegRepresentation(compressionQuality: CGFloat) -> Data? {
  137. #if os(macOS)
  138. guard let cgImage = cgImage else {
  139. return nil
  140. }
  141. let rep = NSBitmapImageRep(cgImage: cgImage)
  142. return rep.representation(using:.jpeg, properties: [.compressionFactor: compressionQuality])
  143. #else
  144. return base.jpegData(compressionQuality: compressionQuality)
  145. #endif
  146. }
  147. // MARK: - GIF
  148. /// Returns GIF representation of `base` image.
  149. ///
  150. /// - Returns: Original GIF data of image.
  151. public func gifRepresentation() -> Data? {
  152. return animatedImageData
  153. }
  154. }
  155. // MARK: - Create images from data
  156. extension KingfisherClass where Base: Image {
  157. /// Creates an animated image from a given data and options. Currently only GIF data is supported.
  158. ///
  159. /// - Parameters:
  160. /// - data: The animated image data.
  161. /// - options: Options to use when creating the animated image.
  162. /// - Returns: An `Image` object represents the animated image. It is in form of an array of image frames with a
  163. /// certain duration. `nil` if anything wrong when creating animated image.
  164. public static func animatedImage(data: Data, options: ImageCreatingOptions) -> Image? {
  165. let info: [String: Any] = [
  166. kCGImageSourceShouldCache as String: true,
  167. kCGImageSourceTypeIdentifierHint as String: kUTTypeGIF
  168. ]
  169. guard let imageSource = CGImageSourceCreateWithData(data as CFData, info as CFDictionary) else {
  170. return nil
  171. }
  172. #if os(macOS)
  173. guard let animatedImage = GIFAnimatedImage(from: imageSource, for: info, options: options) else {
  174. return nil
  175. }
  176. let image: Image?
  177. if options.onlyFirstFrame {
  178. image = animatedImage.images.first
  179. } else {
  180. image = Image(data: data)
  181. let kf = image?.kf
  182. kf?.images = animatedImage.images
  183. kf?.duration = animatedImage.duration
  184. }
  185. image?.kf.animatedImageData = data
  186. return image
  187. #else
  188. let image: Image?
  189. if options.preloadAll || options.onlyFirstFrame {
  190. // Use `images` image if you want to preload all animated data
  191. guard let animatedImage = GIFAnimatedImage(from: imageSource, for: info, options: options) else {
  192. return nil
  193. }
  194. if options.onlyFirstFrame {
  195. image = animatedImage.images.first
  196. } else {
  197. let duration = options.duration <= 0.0 ? animatedImage.duration : options.duration
  198. image = .animatedImage(with: animatedImage.images, duration: duration)
  199. }
  200. image?.kf.animatedImageData = data
  201. } else {
  202. image = Image(data: data, scale: options.scale)
  203. let kf = image?.kf
  204. kf?.imageSource = imageSource
  205. kf?.animatedImageData = data
  206. }
  207. return image
  208. #endif
  209. }
  210. public static func image(data: Data, options: ImageCreatingOptions) -> Image? {
  211. var image: Image?
  212. switch data.kf.imageFormat {
  213. case .JPEG:
  214. image = Image(data: data, scale: options.scale)
  215. case .PNG:
  216. image = Image(data: data, scale: options.scale)
  217. case .GIF:
  218. image = KingfisherClass.animatedImage(data: data, options: options)
  219. case .unknown:
  220. image = Image(data: data, scale: options.scale)
  221. }
  222. return image
  223. }
  224. }