Image.swift 12 KB

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