Image.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  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 KingfisherWrapper 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 bytes.
  81. var cost: Int {
  82. let pixel = Int(size.width * size.height * scale * scale)
  83. guard let cgImage = cgImage else {
  84. return pixel * 4
  85. }
  86. return pixel * cgImage.bitsPerPixel / 8
  87. }
  88. }
  89. // MARK: - Image Conversion
  90. extension KingfisherWrapper 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 KingfisherWrapper 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. #if swift(>=4.2)
  131. return base.pngData()
  132. #else
  133. return UIImagePNGRepresentation(base)
  134. #endif
  135. #endif
  136. }
  137. // MARK: - JPEG
  138. /// Returns JPEG representation of `base` image.
  139. ///
  140. /// - Parameter compressionQuality: The compression quality when converting image to JPEG data.
  141. /// - Returns: JPEG data of image.
  142. public func jpegRepresentation(compressionQuality: CGFloat) -> Data? {
  143. #if os(macOS)
  144. guard let cgImage = cgImage else {
  145. return nil
  146. }
  147. let rep = NSBitmapImageRep(cgImage: cgImage)
  148. return rep.representation(using:.jpeg, properties: [.compressionFactor: compressionQuality])
  149. #else
  150. #if swift(>=4.2)
  151. return base.jpegData(compressionQuality: compressionQuality)
  152. #else
  153. return UIImageJPEGRepresentation(base, compressionQuality)
  154. #endif
  155. #endif
  156. }
  157. // MARK: - GIF
  158. /// Returns GIF representation of `base` image.
  159. ///
  160. /// - Returns: Original GIF data of image.
  161. public func gifRepresentation() -> Data? {
  162. return animatedImageData
  163. }
  164. }
  165. // MARK: - Create images from data
  166. extension KingfisherWrapper where Base: Image {
  167. /// Creates an animated image from a given data and options. Currently only GIF data is supported.
  168. ///
  169. /// - Parameters:
  170. /// - data: The animated image data.
  171. /// - options: Options to use when creating the animated image.
  172. /// - Returns: An `Image` object represents the animated image. It is in form of an array of image frames with a
  173. /// certain duration. `nil` if anything wrong when creating animated image.
  174. public static func animatedImage(data: Data, options: ImageCreatingOptions) -> Image? {
  175. let info: [String: Any] = [
  176. kCGImageSourceShouldCache as String: true,
  177. kCGImageSourceTypeIdentifierHint as String: kUTTypeGIF
  178. ]
  179. guard let imageSource = CGImageSourceCreateWithData(data as CFData, info as CFDictionary) else {
  180. return nil
  181. }
  182. #if os(macOS)
  183. guard let animatedImage = GIFAnimatedImage(from: imageSource, for: info, options: options) else {
  184. return nil
  185. }
  186. let image: Image?
  187. if options.onlyFirstFrame {
  188. image = animatedImage.images.first
  189. } else {
  190. image = Image(data: data)
  191. var kf = image?.kf
  192. kf?.images = animatedImage.images
  193. kf?.duration = animatedImage.duration
  194. }
  195. image?.kf.animatedImageData = data
  196. return image
  197. #else
  198. let image: Image?
  199. if options.preloadAll || options.onlyFirstFrame {
  200. // Use `images` image if you want to preload all animated data
  201. guard let animatedImage = GIFAnimatedImage(from: imageSource, for: info, options: options) else {
  202. return nil
  203. }
  204. if options.onlyFirstFrame {
  205. image = animatedImage.images.first
  206. } else {
  207. let duration = options.duration <= 0.0 ? animatedImage.duration : options.duration
  208. image = .animatedImage(with: animatedImage.images, duration: duration)
  209. }
  210. image?.kf.animatedImageData = data
  211. } else {
  212. image = Image(data: data, scale: options.scale)
  213. var kf = image?.kf
  214. kf?.imageSource = imageSource
  215. kf?.animatedImageData = data
  216. }
  217. return image
  218. #endif
  219. }
  220. /// Creates an image from a given data and options. `.JPEG`, `.PNG` or `.GIF` is supported. For other
  221. /// image format, image initilizer from system will be used. If no image object could be created from
  222. /// the given `data`, `nil` will be returned.
  223. ///
  224. /// - Parameters:
  225. /// - data: The image data representation.
  226. /// - options: Options to use when creating the image.
  227. /// - Returns: An `Image` object represents the image if created. If the `data` is invalid or not supported, `nil`
  228. /// will be returned.
  229. public static func image(data: Data, options: ImageCreatingOptions) -> Image? {
  230. var image: Image?
  231. switch data.kf.imageFormat {
  232. case .JPEG:
  233. image = Image(data: data, scale: options.scale)
  234. case .PNG:
  235. image = Image(data: data, scale: options.scale)
  236. case .GIF:
  237. image = KingfisherWrapper.animatedImage(data: data, options: options)
  238. case .unknown:
  239. image = Image(data: data, scale: options.scale)
  240. }
  241. return image
  242. }
  243. /// Creates a downsampled image from given data to a certain size and scale.
  244. ///
  245. /// - Parameters:
  246. /// - data: The image data contains a JPEG or PNG image.
  247. /// - pointSize: The target size in point to which the image should be downsampled.
  248. /// - scale: The scale of result image.
  249. /// - Returns: A downsampled `Image` object following the input conditions.
  250. ///
  251. /// - Note:
  252. /// Different from image `resize` methods, downsampling will not render the original
  253. /// input image in pixel format. It does downsampling from the image data, so it is much
  254. /// more memory efficient and friendly. Choose to use downsampling as possible as you can.
  255. ///
  256. /// The input size should be smaller than the size of input image. If it is larger than the
  257. /// original image size, the result image will be the same size of input without downsampling.
  258. public static func downsampledImage(data: Data, to pointSize: CGSize, scale: CGFloat) -> Image? {
  259. let imageSourceOptions = [kCGImageSourceShouldCache: false] as CFDictionary
  260. guard let imageSource = CGImageSourceCreateWithData(data as CFData, imageSourceOptions) else {
  261. return nil
  262. }
  263. let maxDimensionInPixels = max(pointSize.width, pointSize.height) * scale
  264. let downsampleOptions = [
  265. kCGImageSourceCreateThumbnailFromImageAlways: true,
  266. kCGImageSourceShouldCacheImmediately: true,
  267. kCGImageSourceCreateThumbnailWithTransform: true,
  268. kCGImageSourceThumbnailMaxPixelSize: maxDimensionInPixels] as CFDictionary
  269. let downsampledImage = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, downsampleOptions)!
  270. return KingfisherWrapper.image(cgImage: downsampledImage, scale: scale, refImage: nil)
  271. }
  272. }