Image.swift 17 KB

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