Image.swift 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  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. }
  81. // MARK: - Image Conversion
  82. extension KingfisherClass where Base: Image {
  83. #if os(macOS)
  84. static func image(cgImage: CGImage, scale: CGFloat, refImage: Image?) -> Image {
  85. return Image(cgImage: cgImage, size: .zero)
  86. }
  87. /// Normalize the image. This getter does nothing on macOS but return the image itself.
  88. public var normalized: Image { return base }
  89. #else
  90. /// Creating an image from a give `CGImage` at scale and orientation for refImage. The method signature is for
  91. /// compability of macOS version.
  92. static func image(cgImage: CGImage, scale: CGFloat, refImage: Image?) -> Image {
  93. return Image(cgImage: cgImage, scale: scale, orientation: refImage?.imageOrientation ?? .up)
  94. }
  95. /// Normalized image of current `base`.
  96. /// This method will try to redraw an image with orientation and scale considered.
  97. public var normalized: Image {
  98. // prevent animated image (GIF) lose it's images
  99. guard images == nil else { return base }
  100. // No need to do anything if already up
  101. guard base.imageOrientation != .up else { return base }
  102. return draw(to: size) { _ in
  103. base.draw(in: CGRect(origin: .zero, size: size))
  104. }
  105. }
  106. #endif
  107. }
  108. // MARK: - Image Representation
  109. extension KingfisherClass where Base: Image {
  110. // MARK: - PNG
  111. /// Returns PNG representation of `base` image.
  112. ///
  113. /// - Returns: PNG data of image.
  114. public func pngRepresentation() -> Data? {
  115. #if os(macOS)
  116. guard let cgimage = cgImage else {
  117. return nil
  118. }
  119. let rep = NSBitmapImageRep(cgImage: cgimage)
  120. return rep.representation(using: .png, properties: [:])
  121. #else
  122. return base.pngData()
  123. #endif
  124. }
  125. // MARK: - JPEG
  126. /// Returns JPEG representation of `base` image.
  127. ///
  128. /// - Parameter compressionQuality: The compression quality when converting image to JPEG data.
  129. /// - Returns: JPEG data of image.
  130. public func jpegRepresentation(compressionQuality: CGFloat) -> Data? {
  131. #if os(macOS)
  132. guard let cgImage = cgImage else {
  133. return nil
  134. }
  135. let rep = NSBitmapImageRep(cgImage: cgImage)
  136. return rep.representation(using:.jpeg, properties: [.compressionFactor: compressionQuality])
  137. #else
  138. return base.jpegData(compressionQuality: compressionQuality)
  139. #endif
  140. }
  141. // MARK: - GIF
  142. /// Returns GIF representation of `base` image.
  143. ///
  144. /// - Returns: Original GIF data of image.
  145. public func gifRepresentation() -> Data? {
  146. return animatedImageData
  147. }
  148. }
  149. // MARK: - Create images from data
  150. extension KingfisherClass where Base: Image {
  151. /// Creates an animated image from a given data and options. Currently only GIF data is supported.
  152. ///
  153. /// - Parameters:
  154. /// - data: The animated image data.
  155. /// - options: Options to use when creating the animated image.
  156. /// - Returns: An `Image` object represents the animated image. It is in form of an array of image frames with a
  157. /// certain duration. `nil` if anything wrong when creating animated image.
  158. public static func animatedImage(data: Data, options: ImageCreatingOptions) -> Image? {
  159. let info: [String: Any] = [
  160. kCGImageSourceShouldCache as String: true,
  161. kCGImageSourceTypeIdentifierHint as String: kUTTypeGIF
  162. ]
  163. guard let imageSource = CGImageSourceCreateWithData(data as CFData, info as CFDictionary) else {
  164. return nil
  165. }
  166. #if os(macOS)
  167. guard let animatedImage = GIFAnimatedImage(from: imageSource, for: info, options: options) else {
  168. return nil
  169. }
  170. let image: Image?
  171. if options.onlyFirstFrame {
  172. image = animatedImage.images.first
  173. } else {
  174. image = Image(data: data)
  175. let kf = image?.kf
  176. kf?.images = animatedImage.images
  177. kf?.duration = animatedImage.duration
  178. }
  179. image?.kf.animatedImageData = data
  180. return image
  181. #else
  182. let image: Image?
  183. if options.preloadAll || options.onlyFirstFrame {
  184. // Use `images` image if you want to preload all animated data
  185. guard let animatedImage = GIFAnimatedImage(from: imageSource, for: info, options: options) else {
  186. return nil
  187. }
  188. if options.onlyFirstFrame {
  189. image = animatedImage.images.first
  190. } else {
  191. let duration = options.duration <= 0.0 ? animatedImage.duration : options.duration
  192. image = .animatedImage(with: animatedImage.images, duration: duration)
  193. }
  194. image?.kf.animatedImageData = data
  195. } else {
  196. image = Image(data: data, scale: options.scale)
  197. let kf = image?.kf
  198. kf?.imageSource = imageSource
  199. kf?.animatedImageData = data
  200. }
  201. return image
  202. #endif
  203. }
  204. public static func image(data: Data, options: ImageCreatingOptions) -> Image? {
  205. var image: Image?
  206. switch data.kf.imageFormat {
  207. case .JPEG:
  208. image = Image(data: data, scale: options.scale)
  209. case .PNG:
  210. image = Image(data: data, scale: options.scale)
  211. case .GIF:
  212. image = KingfisherClass.animatedImage(data: data, options: options)
  213. case .unknown:
  214. image = Image(data: data, scale: options.scale)
  215. }
  216. return image
  217. }
  218. }