Image.swift 9.4 KB

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