Image.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  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. private var imageFrameCountKey: Void?
  42. // MARK: - Image Properties
  43. extension KingfisherWrapper where Base: KFCrossPlatformImage {
  44. private(set) var animatedImageData: Data? {
  45. get { return getAssociatedObject(base, &animatedImageDataKey) }
  46. set { setRetainedAssociatedObject(base, &animatedImageDataKey, newValue) }
  47. }
  48. public var imageFrameCount: Int? {
  49. get { return getAssociatedObject(base, &imageFrameCountKey) }
  50. set { setRetainedAssociatedObject(base, &imageFrameCountKey, newValue) }
  51. }
  52. #if os(macOS)
  53. var cgImage: CGImage? {
  54. return base.cgImage(forProposedRect: nil, context: nil, hints: nil)
  55. }
  56. var scale: CGFloat {
  57. return 1.0
  58. }
  59. private(set) var images: [KFCrossPlatformImage]? {
  60. get { return getAssociatedObject(base, &imagesKey) }
  61. set { setRetainedAssociatedObject(base, &imagesKey, newValue) }
  62. }
  63. private(set) var duration: TimeInterval {
  64. get { return getAssociatedObject(base, &durationKey) ?? 0.0 }
  65. set { setRetainedAssociatedObject(base, &durationKey, newValue) }
  66. }
  67. var size: CGSize {
  68. return base.representations.reduce(.zero) { size, rep in
  69. let width = max(size.width, CGFloat(rep.pixelsWide))
  70. let height = max(size.height, CGFloat(rep.pixelsHigh))
  71. return CGSize(width: width, height: height)
  72. }
  73. }
  74. #else
  75. var cgImage: CGImage? { return base.cgImage }
  76. var scale: CGFloat { return base.scale }
  77. var images: [KFCrossPlatformImage]? { return base.images }
  78. var duration: TimeInterval { return base.duration }
  79. var size: CGSize { return base.size }
  80. /// The image source reference of current image.
  81. public var imageSource: CGImageSource? {
  82. get {
  83. guard let frameSource = frameSource as? CGImageFrameSource else { return nil }
  84. return frameSource.imageSource
  85. }
  86. }
  87. /// The custom frame source of current image.
  88. public private(set) var frameSource: ImageFrameSource? {
  89. get { return getAssociatedObject(base, &imageSourceKey) }
  90. set { setRetainedAssociatedObject(base, &imageSourceKey, newValue) }
  91. }
  92. #endif
  93. // Bitmap memory cost with bytes.
  94. var cost: Int {
  95. let pixel = Int(size.width * size.height * scale * scale)
  96. guard let cgImage = cgImage else {
  97. return pixel * 4
  98. }
  99. let bytesPerPixel = cgImage.bitsPerPixel / 8
  100. guard let imageCount = images?.count else {
  101. return pixel * bytesPerPixel
  102. }
  103. return pixel * bytesPerPixel * imageCount
  104. }
  105. }
  106. // MARK: - Image Conversion
  107. extension KingfisherWrapper where Base: KFCrossPlatformImage {
  108. #if os(macOS)
  109. static func image(cgImage: CGImage, scale: CGFloat, refImage: KFCrossPlatformImage?) -> KFCrossPlatformImage {
  110. return KFCrossPlatformImage(cgImage: cgImage, size: .zero)
  111. }
  112. /// Normalize the image. This getter does nothing on macOS but return the image itself.
  113. public var normalized: KFCrossPlatformImage { return base }
  114. #else
  115. /// Creating an image from a give `CGImage` at scale and orientation for refImage. The method signature is for
  116. /// compatibility of macOS version.
  117. static func image(cgImage: CGImage, scale: CGFloat, refImage: KFCrossPlatformImage?) -> KFCrossPlatformImage {
  118. return KFCrossPlatformImage(cgImage: cgImage, scale: scale, orientation: refImage?.imageOrientation ?? .up)
  119. }
  120. /// Returns normalized image for current `base` image.
  121. /// This method will try to redraw an image with orientation and scale considered.
  122. public var normalized: KFCrossPlatformImage {
  123. // prevent animated image (GIF) lose it's images
  124. guard images == nil else { return base.copy() as! KFCrossPlatformImage }
  125. // No need to do anything if already up
  126. guard base.imageOrientation != .up else { return base.copy() as! KFCrossPlatformImage }
  127. return draw(to: size, inverting: true, refImage: KFCrossPlatformImage()) {
  128. fixOrientation(in: $0)
  129. return true
  130. }
  131. }
  132. func fixOrientation(in context: CGContext) {
  133. var transform = CGAffineTransform.identity
  134. let orientation = base.imageOrientation
  135. switch orientation {
  136. case .down, .downMirrored:
  137. transform = transform.translatedBy(x: size.width, y: size.height)
  138. transform = transform.rotated(by: .pi)
  139. case .left, .leftMirrored:
  140. transform = transform.translatedBy(x: size.width, y: 0)
  141. transform = transform.rotated(by: .pi / 2.0)
  142. case .right, .rightMirrored:
  143. transform = transform.translatedBy(x: 0, y: size.height)
  144. transform = transform.rotated(by: .pi / -2.0)
  145. case .up, .upMirrored:
  146. break
  147. #if compiler(>=5)
  148. @unknown default:
  149. break
  150. #endif
  151. }
  152. //Flip image one more time if needed to, this is to prevent flipped image
  153. switch orientation {
  154. case .upMirrored, .downMirrored:
  155. transform = transform.translatedBy(x: size.width, y: 0)
  156. transform = transform.scaledBy(x: -1, y: 1)
  157. case .leftMirrored, .rightMirrored:
  158. transform = transform.translatedBy(x: size.height, y: 0)
  159. transform = transform.scaledBy(x: -1, y: 1)
  160. case .up, .down, .left, .right:
  161. break
  162. #if compiler(>=5)
  163. @unknown default:
  164. break
  165. #endif
  166. }
  167. context.concatenate(transform)
  168. switch orientation {
  169. case .left, .leftMirrored, .right, .rightMirrored:
  170. context.draw(cgImage!, in: CGRect(x: 0, y: 0, width: size.height, height: size.width))
  171. default:
  172. context.draw(cgImage!, in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
  173. }
  174. }
  175. #endif
  176. }
  177. // MARK: - Image Representation
  178. extension KingfisherWrapper where Base: KFCrossPlatformImage {
  179. /// Returns PNG representation of `base` image.
  180. ///
  181. /// - Returns: PNG data of image.
  182. public func pngRepresentation() -> Data? {
  183. #if os(macOS)
  184. guard let cgImage = cgImage else {
  185. return nil
  186. }
  187. let rep = NSBitmapImageRep(cgImage: cgImage)
  188. return rep.representation(using: .png, properties: [:])
  189. #else
  190. return base.pngData()
  191. #endif
  192. }
  193. /// Returns JPEG representation of `base` image.
  194. ///
  195. /// - Parameter compressionQuality: The compression quality when converting image to JPEG data.
  196. /// - Returns: JPEG data of image.
  197. public func jpegRepresentation(compressionQuality: CGFloat) -> Data? {
  198. #if os(macOS)
  199. guard let cgImage = cgImage else {
  200. return nil
  201. }
  202. let rep = NSBitmapImageRep(cgImage: cgImage)
  203. return rep.representation(using:.jpeg, properties: [.compressionFactor: compressionQuality])
  204. #else
  205. return base.jpegData(compressionQuality: compressionQuality)
  206. #endif
  207. }
  208. /// Returns GIF representation of `base` image.
  209. ///
  210. /// - Returns: Original GIF data of image.
  211. public func gifRepresentation() -> Data? {
  212. return animatedImageData
  213. }
  214. /// Returns a data representation for `base` image, with the `format` as the format indicator.
  215. /// - Parameters:
  216. /// - format: The format in which the output data should be. If `unknown`, the `base` image will be
  217. /// converted in the PNG representation.
  218. /// - compressionQuality: The compression quality when converting image to a lossy format data.
  219. ///
  220. /// - Returns: The output data representing.
  221. public func data(format: ImageFormat, compressionQuality: CGFloat = 1.0) -> Data? {
  222. return autoreleasepool { () -> Data? in
  223. let data: Data?
  224. switch format {
  225. case .PNG: data = pngRepresentation()
  226. case .JPEG: data = jpegRepresentation(compressionQuality: compressionQuality)
  227. case .GIF: data = gifRepresentation()
  228. case .unknown: data = normalized.kf.pngRepresentation()
  229. }
  230. return data
  231. }
  232. }
  233. }
  234. // MARK: - Creating Images
  235. extension KingfisherWrapper where Base: KFCrossPlatformImage {
  236. /// Creates an animated image from a given data and options. Currently only GIF data is supported.
  237. ///
  238. /// - Parameters:
  239. /// - data: The animated image data.
  240. /// - options: Options to use when creating the animated image.
  241. /// - Returns: An `Image` object represents the animated image. It is in form of an array of image frames with a
  242. /// certain duration. `nil` if anything wrong when creating animated image.
  243. public static func animatedImage(data: Data, options: ImageCreatingOptions) -> KFCrossPlatformImage? {
  244. let info: [String: Any] = [
  245. kCGImageSourceShouldCache as String: true,
  246. kCGImageSourceTypeIdentifierHint as String: kUTTypeGIF
  247. ]
  248. guard let imageSource = CGImageSourceCreateWithData(data as CFData, info as CFDictionary) else {
  249. return nil
  250. }
  251. let frameSource = CGImageFrameSource(data: data, imageSource: imageSource, options: info)
  252. #if os(macOS)
  253. let baseImage = KFCrossPlatformImage(data: data)
  254. #else
  255. let baseImage = KFCrossPlatformImage(data: data, scale: options.scale)
  256. #endif
  257. return animatedImage(source: frameSource, options: options, baseImage: baseImage)
  258. }
  259. /// Creates an animated image from a given frame source.
  260. ///
  261. /// - Parameters:
  262. /// - source: The frame source to create animated image from.
  263. /// - options: Options to use when creating the animated image.
  264. /// - baseImage: An optional image object to be used as the key frame of the animated image. If `nil`, the first
  265. /// frame of the `source` will be used.
  266. /// - Returns: An `Image` object represents the animated image. It is in form of an array of image frames with a
  267. /// certain duration. `nil` if anything wrong when creating animated image.
  268. public static func animatedImage(source: ImageFrameSource, options: ImageCreatingOptions, baseImage: KFCrossPlatformImage? = nil) -> KFCrossPlatformImage? {
  269. #if os(macOS)
  270. guard let animatedImage = GIFAnimatedImage(from: source, options: options) else {
  271. return nil
  272. }
  273. var image: KFCrossPlatformImage?
  274. if options.onlyFirstFrame {
  275. image = animatedImage.images.first
  276. } else {
  277. if let baseImage = baseImage {
  278. image = baseImage
  279. } else {
  280. image = animatedImage.images.first
  281. }
  282. var kf = image?.kf
  283. kf?.images = animatedImage.images
  284. kf?.duration = animatedImage.duration
  285. }
  286. image?.kf.animatedImageData = source.data
  287. image?.kf.imageFrameCount = source.frameCount
  288. return image
  289. #else
  290. var image: KFCrossPlatformImage?
  291. if options.preloadAll || options.onlyFirstFrame {
  292. // Use `images` image if you want to preload all animated data
  293. guard let animatedImage = GIFAnimatedImage(from: source, options: options) else {
  294. return nil
  295. }
  296. if options.onlyFirstFrame {
  297. image = animatedImage.images.first
  298. } else {
  299. let duration = options.duration <= 0.0 ? animatedImage.duration : options.duration
  300. image = .animatedImage(with: animatedImage.images, duration: duration)
  301. }
  302. image?.kf.animatedImageData = source.data
  303. } else {
  304. if let baseImage = baseImage {
  305. image = baseImage
  306. } else {
  307. guard let firstFrame = source.frame(at: 0) else {
  308. return nil
  309. }
  310. image = KFCrossPlatformImage(cgImage: firstFrame, scale: options.scale, orientation: .up)
  311. }
  312. var kf = image?.kf
  313. kf?.frameSource = source
  314. kf?.animatedImageData = source.data
  315. }
  316. image?.kf.imageFrameCount = source.frameCount
  317. return image
  318. #endif
  319. }
  320. /// Creates an image from a given data and options. `.JPEG`, `.PNG` or `.GIF` is supported. For other
  321. /// image format, image initializer from system will be used. If no image object could be created from
  322. /// the given `data`, `nil` will be returned.
  323. ///
  324. /// - Parameters:
  325. /// - data: The image data representation.
  326. /// - options: Options to use when creating the image.
  327. /// - Returns: An `Image` object represents the image if created. If the `data` is invalid or not supported, `nil`
  328. /// will be returned.
  329. public static func image(data: Data, options: ImageCreatingOptions) -> KFCrossPlatformImage? {
  330. var image: KFCrossPlatformImage?
  331. switch data.kf.imageFormat {
  332. case .JPEG:
  333. image = KFCrossPlatformImage(data: data, scale: options.scale)
  334. case .PNG:
  335. image = KFCrossPlatformImage(data: data, scale: options.scale)
  336. case .GIF:
  337. image = KingfisherWrapper.animatedImage(data: data, options: options)
  338. case .unknown:
  339. image = KFCrossPlatformImage(data: data, scale: options.scale)
  340. }
  341. return image
  342. }
  343. /// Creates a downsampled image from given data to a certain size and scale.
  344. ///
  345. /// - Parameters:
  346. /// - data: The image data contains a JPEG or PNG image.
  347. /// - pointSize: The target size in point to which the image should be downsampled.
  348. /// - scale: The scale of result image.
  349. /// - Returns: A downsampled `Image` object following the input conditions.
  350. ///
  351. /// - Note:
  352. /// Different from image `resize` methods, downsampling will not render the original
  353. /// input image in pixel format. It does downsampling from the image data, so it is much
  354. /// more memory efficient and friendly. Choose to use downsampling as possible as you can.
  355. ///
  356. /// The pointsize should be smaller than the size of input image. If it is larger than the
  357. /// original image size, the result image will be the same size of input without downsampling.
  358. public static func downsampledImage(data: Data, to pointSize: CGSize, scale: CGFloat) -> KFCrossPlatformImage? {
  359. let imageSourceOptions = [kCGImageSourceShouldCache: false] as CFDictionary
  360. guard let imageSource = CGImageSourceCreateWithData(data as CFData, imageSourceOptions) else {
  361. return nil
  362. }
  363. let maxDimensionInPixels = max(pointSize.width, pointSize.height) * scale
  364. let downsampleOptions: [CFString : Any] = [
  365. kCGImageSourceCreateThumbnailFromImageAlways: true,
  366. kCGImageSourceShouldCacheImmediately: true,
  367. kCGImageSourceCreateThumbnailWithTransform: true,
  368. kCGImageSourceThumbnailMaxPixelSize: maxDimensionInPixels
  369. ]
  370. guard let downsampledImage = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, downsampleOptions as CFDictionary) else {
  371. return nil
  372. }
  373. return KingfisherWrapper.image(cgImage: downsampledImage, scale: scale, refImage: nil)
  374. }
  375. }