ImageDataProvider.swift 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. //
  2. // ImageDataProvider.swift
  3. // Kingfisher
  4. //
  5. // Created by onevcat on 2018/11/13.
  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 data provider to provide image data to Kingfisher when setting with
  29. /// ``Source/provider(_:)`` source. Compared to ``Source/network(_:)`` member, it gives a chance
  30. /// to load some image data in your own way, as long as you can provide the data
  31. /// representation for the image.
  32. public protocol ImageDataProvider: Sendable {
  33. /// The key used in cache.
  34. var cacheKey: String { get }
  35. /// Provides the data which represents image. Kingfisher uses the data you pass in the
  36. /// handler to process images and caches it for later use.
  37. ///
  38. /// - Parameter handler: The handler you should call when you prepared your data.
  39. /// If the data is loaded successfully, call the handler with
  40. /// a `.success` with the data associated. Otherwise, call it
  41. /// with a `.failure` and pass the error.
  42. ///
  43. /// - Note: If the `handler` is called with a `.failure` with error,
  44. /// a ``KingfisherError/ImageSettingErrorReason/dataProviderError(provider:error:)`` will be finally thrown out to
  45. /// you as the ``KingfisherError`` from the framework.
  46. func data(handler: @escaping @Sendable (Result<Data, any Error>) -> Void)
  47. /// The content URL represents this provider, if exists.
  48. var contentURL: URL? { get }
  49. }
  50. extension ImageDataProvider {
  51. func data() async throws -> Data {
  52. try await withCheckedThrowingContinuation { continuation in
  53. data(handler: { continuation.resume(with: $0) })
  54. }
  55. }
  56. }
  57. public extension ImageDataProvider {
  58. var contentURL: URL? { return nil }
  59. func convertToSource() -> Source {
  60. .provider(self)
  61. }
  62. }
  63. /// Represents an image data provider for loading from a local file URL on disk.
  64. /// Uses this type for adding a disk image to Kingfisher. Compared to loading it
  65. /// directly, you can get benefit of using Kingfisher's extension methods, as well
  66. /// as applying ``ImageProcessor``s and storing the image to ``ImageCache`` of Kingfisher.
  67. public struct LocalFileImageDataProvider: ImageDataProvider {
  68. // MARK: Public Properties
  69. /// The file URL from which the image be loaded.
  70. public let fileURL: URL
  71. private let loadingQueue: ExecutionQueue
  72. // MARK: Initializers
  73. /// Creates an image data provider by supplying the target local file URL.
  74. ///
  75. /// - Parameters:
  76. /// - fileURL: The file URL from which the image be loaded.
  77. /// - cacheKey: The key is used for caching the image data. By default,
  78. /// the `absoluteString` of ``LocalFileImageDataProvider/fileURL`` is used.
  79. /// - loadingQueue: The queue where the file loading should happen. By default, the dispatch queue of
  80. /// `.global(qos: .userInitiated)` will be used.
  81. public init(
  82. fileURL: URL,
  83. cacheKey: String? = nil,
  84. loadingQueue: ExecutionQueue = .dispatch(DispatchQueue.global(qos: .userInitiated))
  85. ) {
  86. self.fileURL = fileURL
  87. self.cacheKey = cacheKey ?? fileURL.localFileCacheKey
  88. self.loadingQueue = loadingQueue
  89. }
  90. // MARK: Protocol Conforming
  91. /// The key used in cache.
  92. public var cacheKey: String
  93. public func data(handler: @escaping @Sendable (Result<Data, any Error>) -> Void) {
  94. loadingQueue.execute {
  95. handler(Result(catching: { try Data(contentsOf: fileURL) }))
  96. }
  97. }
  98. public var data: Data {
  99. get async throws {
  100. try await withCheckedThrowingContinuation { continuation in
  101. loadingQueue.execute {
  102. do {
  103. let data = try Data(contentsOf: fileURL)
  104. continuation.resume(returning: data)
  105. } catch {
  106. continuation.resume(throwing: error)
  107. }
  108. }
  109. }
  110. }
  111. }
  112. /// The URL of the local file on the disk.
  113. public var contentURL: URL? {
  114. return fileURL
  115. }
  116. }
  117. /// Represents an image data provider for loading image from a given Base64 encoded string.
  118. public struct Base64ImageDataProvider: ImageDataProvider {
  119. // MARK: Public Properties
  120. /// The encoded Base64 string for the image.
  121. public let base64String: String
  122. // MARK: Initializers
  123. /// Creates an image data provider by supplying the Base64 encoded string.
  124. ///
  125. /// - Parameters:
  126. /// - base64String: The Base64 encoded string for an image.
  127. /// - cacheKey: The key is used for caching the image data. You need a different key for any different image.
  128. public init(base64String: String, cacheKey: String) {
  129. self.base64String = base64String
  130. self.cacheKey = cacheKey
  131. }
  132. // MARK: Protocol Conforming
  133. /// The key used in cache.
  134. public var cacheKey: String
  135. public func data(handler: (Result<Data, any Error>) -> Void) {
  136. let data = Data(base64Encoded: base64String)!
  137. handler(.success(data))
  138. }
  139. }
  140. /// Represents an image data provider for a raw data object.
  141. public struct RawImageDataProvider: ImageDataProvider {
  142. // MARK: Public Properties
  143. /// The raw data object to provide to Kingfisher image loader.
  144. public let data: Data
  145. // MARK: Initializers
  146. /// Creates an image data provider by the given raw `data` value and a `cacheKey` be used in Kingfisher cache.
  147. ///
  148. /// - Parameters:
  149. /// - data: The raw data represents an image.
  150. /// - cacheKey: The key is used for caching the image data. You need a different key for any different image.
  151. public init(data: Data, cacheKey: String) {
  152. self.data = data
  153. self.cacheKey = cacheKey
  154. }
  155. // MARK: Protocol Conforming
  156. /// The key used in cache.
  157. public var cacheKey: String
  158. public func data(handler: @escaping (Result<Data, any Error>) -> Void) {
  159. handler(.success(data))
  160. }
  161. }
  162. /// A data provider that creates a thumbnail from a URL using Core Graphics.
  163. public struct ThumbnailImageDataProvider: ImageDataProvider {
  164. public enum ThumbnailImageDataProviderError: Error {
  165. case invalidImageSource
  166. case invalidThumbnail
  167. case writeDataError
  168. case finalizeDataError
  169. }
  170. /// The URL from which to load the image
  171. public let url: URL
  172. /// The maximum size of the thumbnail in pixels
  173. public var maxPixelSize: CGFloat
  174. /// Whether to always create a thumbnail even if the image is smaller than maxPixelSize
  175. public var alwaysCreateThumbnail: Bool
  176. /// The cache key for this provider
  177. public var cacheKey: String
  178. /// Creates a new thumbnail data provider
  179. /// - Parameters:
  180. /// - url: The URL from which to load the image
  181. /// - maxPixelSize: The maximum size of the thumbnail in pixels
  182. /// - alwaysCreateThumbnail: Whether to always create a thumbnail even if the image is smaller than maxPixelSize
  183. public init(
  184. url: URL,
  185. maxPixelSize: CGFloat,
  186. alwaysCreateThumbnail: Bool = true,
  187. cacheKey: String? = nil
  188. ) {
  189. self.url = url
  190. self.maxPixelSize = maxPixelSize
  191. self.alwaysCreateThumbnail = alwaysCreateThumbnail
  192. self.cacheKey = cacheKey ?? "\(url.absoluteString)_thumb_\(maxPixelSize)_\(alwaysCreateThumbnail)"
  193. }
  194. public func data(handler: @escaping @Sendable (Result<Data, any Error>) -> Void) {
  195. DispatchQueue.global(qos: .userInitiated).async {
  196. do {
  197. guard let url = URL(string: url.absoluteString) else {
  198. throw KingfisherError.imageSettingError(reason: .emptySource)
  199. }
  200. guard let imageSource = CGImageSourceCreateWithURL(url as CFURL, nil) else {
  201. throw ThumbnailImageDataProviderError.invalidImageSource
  202. }
  203. let options = [
  204. kCGImageSourceThumbnailMaxPixelSize: maxPixelSize,
  205. kCGImageSourceCreateThumbnailFromImageAlways: alwaysCreateThumbnail,
  206. kCGImageSourceCreateThumbnailWithTransform: true
  207. ]
  208. guard let thumbnailRef = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, options as CFDictionary) else {
  209. throw ThumbnailImageDataProviderError.invalidThumbnail
  210. }
  211. let data = NSMutableData()
  212. guard let destination = CGImageDestinationCreateWithData(
  213. data, CGImageSourceGetType(imageSource)!, 1, nil
  214. ) else {
  215. throw ThumbnailImageDataProviderError.writeDataError
  216. }
  217. CGImageDestinationAddImage(destination, thumbnailRef, nil)
  218. if CGImageDestinationFinalize(destination) {
  219. handler(.success(data as Data))
  220. } else {
  221. throw ThumbnailImageDataProviderError.finalizeDataError
  222. }
  223. } catch {
  224. handler(.failure(error))
  225. }
  226. }
  227. }
  228. }