GIFAnimatedImage.swift 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  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 creating options used in Kingfisher.
  29. public struct ImageCreatingOptions {
  30. /// The target scale of image needs to be created.
  31. public let scale: CGFloat
  32. /// The expected animation duration if an animated image being created.
  33. public let duration: TimeInterval
  34. /// For an animated image, whether or not all frames should be loaded before displaying.
  35. public let preloadAll: Bool
  36. /// For an animated image, whether or not only the first image should be
  37. /// loaded as a static image. It is useful for preview purpose of an animated image.
  38. public let onlyFirstFrame: Bool
  39. /// Creates an `ImageCreatingOptions` object.
  40. ///
  41. /// - Parameters:
  42. /// - scale: The target scale of image needs to be created. Default is `1.0`.
  43. /// - duration: The expected animation duration if an animated image being created.
  44. /// A value less 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 or not only the first image should be
  49. /// loaded as a static image. It is useful for preview purpose of 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. self.scale = scale
  58. self.duration = duration
  59. self.preloadAll = preloadAll
  60. self.onlyFirstFrame = onlyFirstFrame
  61. }
  62. }
  63. /// Represents the decoding for a GIF image. This class extracts frames from an `imageSource`, then
  64. /// hold the images for later use.
  65. public class GIFAnimatedImage {
  66. let images: [KFCrossPlatformImage]
  67. let duration: TimeInterval
  68. init?(from frameSource: ImageFrameSource, options: ImageCreatingOptions) {
  69. let frameCount = frameSource.frameCount
  70. var images = [KFCrossPlatformImage]()
  71. var gifDuration = 0.0
  72. for i in 0 ..< frameCount {
  73. guard let imageRef = frameSource.frame(at: i) else {
  74. return nil
  75. }
  76. if frameCount == 1 {
  77. gifDuration = .infinity
  78. } else {
  79. // Get current animated GIF frame duration
  80. gifDuration += frameSource.duration(at: i)
  81. }
  82. images.append(KingfisherWrapper.image(cgImage: imageRef, scale: options.scale, refImage: nil))
  83. if options.onlyFirstFrame { break }
  84. }
  85. self.images = images
  86. self.duration = gifDuration
  87. }
  88. convenience init?(from imageSource: CGImageSource, for info: [String: Any], options: ImageCreatingOptions) {
  89. let frameSource = CGImageFrameSource(data: nil, imageSource: imageSource, options: info)
  90. self.init(from: frameSource, options: options)
  91. }
  92. /// Calculates frame duration for a gif frame out of the kCGImagePropertyGIFDictionary dictionary.
  93. public static func getFrameDuration(from gifInfo: [String: Any]?) -> TimeInterval {
  94. let defaultFrameDuration = 0.1
  95. guard let gifInfo = gifInfo else { return defaultFrameDuration }
  96. let unclampedDelayTime = gifInfo[kCGImagePropertyGIFUnclampedDelayTime as String] as? NSNumber
  97. let delayTime = gifInfo[kCGImagePropertyGIFDelayTime as String] as? NSNumber
  98. let duration = unclampedDelayTime ?? delayTime
  99. guard let frameDuration = duration else { return defaultFrameDuration }
  100. return frameDuration.doubleValue > 0.011 ? frameDuration.doubleValue : defaultFrameDuration
  101. }
  102. /// Calculates frame duration at a specific index for a gif from an `imageSource`.
  103. public static func getFrameDuration(from imageSource: CGImageSource, at index: Int) -> TimeInterval {
  104. guard let properties = CGImageSourceCopyPropertiesAtIndex(imageSource, index, nil)
  105. as? [String: Any] else { return 0.0 }
  106. let gifInfo = properties[kCGImagePropertyGIFDictionary as String] as? [String: Any]
  107. return getFrameDuration(from: gifInfo)
  108. }
  109. }
  110. /// Represents a frame source for animated image
  111. public protocol ImageFrameSource {
  112. /// Source data associated with this frame source.
  113. var data: Data? { get }
  114. /// Count of total frames in this frame source.
  115. var frameCount: Int { get }
  116. /// Retrieves the frame at a specific index. The result image is expected to be
  117. /// no larger than `maxSize`. If the index is invalid, implementors should return `nil`.
  118. func frame(at index: Int, maxSize: CGSize?) -> CGImage?
  119. /// Retrieves the duration at a specific index. If the index is invalid, implementors should return `0.0`.
  120. func duration(at index: Int) -> TimeInterval
  121. }
  122. public extension ImageFrameSource {
  123. /// Retrieves the frame at a specific index. If the index is invalid, implementors should return `nil`.
  124. func frame(at index: Int) -> CGImage? {
  125. return frame(at: index, maxSize: nil)
  126. }
  127. }
  128. struct CGImageFrameSource: ImageFrameSource {
  129. let data: Data?
  130. let imageSource: CGImageSource
  131. let options: [String: Any]?
  132. var frameCount: Int {
  133. return CGImageSourceGetCount(imageSource)
  134. }
  135. func frame(at index: Int, maxSize: CGSize?) -> CGImage? {
  136. var options = self.options as? [CFString: Any]
  137. if let maxSize = maxSize, maxSize != .zero {
  138. options = (options ?? [:]).merging([
  139. kCGImageSourceCreateThumbnailFromImageIfAbsent: true,
  140. kCGImageSourceCreateThumbnailWithTransform: true,
  141. kCGImageSourceShouldCacheImmediately: true,
  142. kCGImageSourceThumbnailMaxPixelSize: max(maxSize.width, maxSize.height)
  143. ], uniquingKeysWith: { $1 })
  144. }
  145. return CGImageSourceCreateImageAtIndex(imageSource, index, options as CFDictionary?)
  146. }
  147. func duration(at index: Int) -> TimeInterval {
  148. return GIFAnimatedImage.getFrameDuration(from: imageSource, at: index)
  149. }
  150. }