GIFAnimatedImage.swift 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. //
  2. // AnimatedImage.swift
  3. // Kingfisher
  4. //
  5. // Created by onevcat on 2018/09/26.
  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. import Foundation
  27. import ImageIO
  28. /// Represents a set of image creation options used in Kingfisher.
  29. public struct ImageCreatingOptions: Equatable {
  30. /// The target scale of the image that needs to be created.
  31. public var scale: CGFloat
  32. /// The expected animation duration if an animated image is being created.
  33. public var duration: TimeInterval
  34. /// For an animated image, indicates whether or not all frames should be loaded before displaying.
  35. public var preloadAll: Bool
  36. /// For an animated image, indicates whether only the first image should be
  37. /// loaded as a static image. It is useful for previewing an animated image.
  38. public var onlyFirstFrame: Bool
  39. /// Creates an `ImageCreatingOptions` object.
  40. ///
  41. /// - Parameters:
  42. /// - scale: The target scale of the image that needs to be created. Default is `1.0`.
  43. /// - duration: The expected animation duration if an animated image is being created.
  44. /// A value less than or equal to `0.0` means the animated image duration will
  45. /// be determined by the frame data. Default is `0.0`.
  46. /// - preloadAll: For an animated image, whether or not all frames should be loaded before displaying.
  47. /// Default is `false`.
  48. /// - onlyFirstFrame: For an animated image, whether only the first image should be
  49. /// loaded as a static image. It is useful for previewing an animated image.
  50. /// Default is `false`.
  51. public init(
  52. scale: CGFloat = 1.0,
  53. duration: TimeInterval = 0.0,
  54. preloadAll: Bool = false,
  55. onlyFirstFrame: Bool = false
  56. )
  57. {
  58. self.scale = scale
  59. self.duration = duration
  60. self.preloadAll = preloadAll
  61. self.onlyFirstFrame = onlyFirstFrame
  62. }
  63. }
  64. /// Represents the decoding for a GIF image. This class extracts frames from an ``ImageFrameSource``, and then
  65. /// holds the images for later use.
  66. public class GIFAnimatedImage {
  67. let images: [KFCrossPlatformImage]
  68. let duration: TimeInterval
  69. init?(from frameSource: any ImageFrameSource, options: ImageCreatingOptions) {
  70. let frameCount = frameSource.frameCount
  71. var images = [KFCrossPlatformImage]()
  72. var gifDuration = 0.0
  73. for i in 0 ..< frameCount {
  74. guard let imageRef = frameSource.frame(at: i) else {
  75. return nil
  76. }
  77. if frameCount == 1 {
  78. gifDuration = .infinity
  79. } else {
  80. // Get current animated GIF frame duration
  81. gifDuration += frameSource.duration(at: i)
  82. }
  83. images.append(KingfisherWrapper.image(cgImage: imageRef, scale: options.scale, refImage: nil))
  84. if options.onlyFirstFrame { break }
  85. }
  86. self.images = images
  87. self.duration = gifDuration
  88. }
  89. convenience init?(from imageSource: CGImageSource, for info: [String: Any], options: ImageCreatingOptions) {
  90. let frameSource = CGImageFrameSource(data: nil, imageSource: imageSource, options: info)
  91. self.init(from: frameSource, options: options)
  92. }
  93. /// Calculates the frame duration for a GIF frame out of the `kCGImagePropertyGIFDictionary` dictionary.
  94. public static func getFrameDuration(from gifInfo: [String: Any]?) -> TimeInterval {
  95. let defaultFrameDuration = 0.1
  96. guard let gifInfo = gifInfo else { return defaultFrameDuration }
  97. let unclampedDelayTime = gifInfo[kCGImagePropertyGIFUnclampedDelayTime as String] as? NSNumber
  98. let delayTime = gifInfo[kCGImagePropertyGIFDelayTime as String] as? NSNumber
  99. let duration = unclampedDelayTime ?? delayTime
  100. guard let frameDuration = duration else { return defaultFrameDuration }
  101. return frameDuration.doubleValue > 0.011 ? frameDuration.doubleValue : defaultFrameDuration
  102. }
  103. /// Calculates the frame duration at a specific index for a GIF from an `CGImageSource`.
  104. ///
  105. /// - Parameters:
  106. /// - imageSource: The image source where the animated image information should be extracted from.
  107. /// - index: The index of the target frame in the image.
  108. /// - Returns: The time duration of the frame at given index in the image.
  109. public static func getFrameDuration(from imageSource: CGImageSource, at index: Int) -> TimeInterval {
  110. guard let properties = CGImageSourceCopyPropertiesAtIndex(imageSource, index, nil)
  111. as? [String: Any] else { return 0.0 }
  112. let gifInfo = properties[kCGImagePropertyGIFDictionary as String] as? [String: Any]
  113. return getFrameDuration(from: gifInfo)
  114. }
  115. }
  116. /// Represents a frame source for an animated image.
  117. public protocol ImageFrameSource {
  118. /// Source data associated with this frame source.
  119. var data: Data? { get }
  120. /// Count of the total frames in this frame source.
  121. var frameCount: Int { get }
  122. /// Retrieves the frame at a specific index.
  123. ///
  124. /// The resulting image is expected to be no larger than `maxSize`. If the index is invalid,
  125. /// implementors should return `nil`.
  126. func frame(at index: Int, maxSize: CGSize?) -> CGImage?
  127. /// Retrieves the duration at a specific index. If the index is invalid, implementors should return `0.0`.
  128. func duration(at index: Int) -> TimeInterval
  129. /// Creates a copy of the current `ImageFrameSource` instance.
  130. ///
  131. /// - Returns: A new instance of the same type as `self` with identical properties.
  132. /// If not overridden by conforming types, this default implementation
  133. /// simply returns `self`, which may not create an actual copy if the type is a reference type.
  134. func copy() -> Self
  135. }
  136. public extension ImageFrameSource {
  137. /// Retrieves the frame at a specific index. If the index is invalid, implementors should return `nil`.
  138. func frame(at index: Int) -> CGImage? {
  139. return frame(at: index, maxSize: nil)
  140. }
  141. func copy() -> Self {
  142. return self
  143. }
  144. }
  145. struct CGImageFrameSource: ImageFrameSource {
  146. let data: Data?
  147. let imageSource: CGImageSource
  148. let options: [String: Any]?
  149. var frameCount: Int {
  150. return CGImageSourceGetCount(imageSource)
  151. }
  152. func frame(at index: Int, maxSize: CGSize?) -> CGImage? {
  153. var options = self.options as? [CFString: Any]
  154. if let maxSize = maxSize, maxSize != .zero {
  155. options = (options ?? [:]).merging([
  156. kCGImageSourceCreateThumbnailFromImageIfAbsent: true,
  157. kCGImageSourceCreateThumbnailWithTransform: true,
  158. kCGImageSourceShouldCacheImmediately: true,
  159. kCGImageSourceThumbnailMaxPixelSize: max(maxSize.width, maxSize.height)
  160. ], uniquingKeysWith: { $1 })
  161. }
  162. return CGImageSourceCreateImageAtIndex(imageSource, index, options as CFDictionary?)
  163. }
  164. func duration(at index: Int) -> TimeInterval {
  165. return GIFAnimatedImage.getFrameDuration(from: imageSource, at: index)
  166. }
  167. func copy() -> Self {
  168. guard let data = data, let source = CGImageSourceCreateWithData(data as CFData, options as CFDictionary?) else {
  169. return self
  170. }
  171. return CGImageFrameSource(data: data, imageSource: source, options: options)
  172. }
  173. }