Image.swift 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  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. #else // os(macOS)
  29. import UIKit
  30. import MobileCoreServices
  31. #endif // os(macOS)
  32. #if !os(watchOS)
  33. import CoreImage
  34. #endif
  35. import CoreGraphics
  36. import ImageIO
  37. #if canImport(UniformTypeIdentifiers)
  38. import UniformTypeIdentifiers
  39. #endif
  40. #if compiler(>=5.10)
  41. nonisolated(unsafe) private let animatedImageDataKey = malloc(1)!
  42. nonisolated(unsafe) private let imageFrameCountKey = malloc(1)!
  43. nonisolated(unsafe) private let imageSourceKey = malloc(1)!
  44. nonisolated(unsafe) private let imageCreatingOptionsKey = malloc(1)!
  45. #if os(macOS)
  46. nonisolated(unsafe) private let imagesKey = malloc(1)!
  47. nonisolated(unsafe) private let durationKey = malloc(1)!
  48. #endif // os(macOS)
  49. #else // compiler(>=5.10)
  50. private let animatedImageDataKey = malloc(1)!
  51. private let imageFrameCountKey = malloc(1)!
  52. private let imageSourceKey = malloc(1)!
  53. private let imageCreatingOptionsKey = malloc(1)!
  54. #if os(macOS)
  55. private let imagesKey = malloc(1)!
  56. private let durationKey = malloc(1)!
  57. #endif // os(macOS)
  58. #endif // compiler(>=5.10)
  59. // MARK: - Image Properties
  60. extension KingfisherWrapper where Base: KFCrossPlatformImage {
  61. private(set) var animatedImageData: Data? {
  62. get { return getAssociatedObject(base, animatedImageDataKey) }
  63. set { setRetainedAssociatedObject(base, animatedImageDataKey, newValue) }
  64. }
  65. private(set) var imageCreatingOptions: ImageCreatingOptions? {
  66. get { return getAssociatedObject(base, imageCreatingOptionsKey) }
  67. set { setRetainedAssociatedObject(base, imageCreatingOptionsKey, newValue) }
  68. }
  69. public var imageFrameCount: Int? {
  70. get { return getAssociatedObject(base, imageFrameCountKey) }
  71. set { setRetainedAssociatedObject(base, imageFrameCountKey, newValue) }
  72. }
  73. #if os(macOS)
  74. var cgImage: CGImage? {
  75. return base.cgImage(forProposedRect: nil, context: nil, hints: nil)
  76. }
  77. var scale: CGFloat {
  78. return 1.0
  79. }
  80. private(set) var images: [KFCrossPlatformImage]? {
  81. get { return getAssociatedObject(base, imagesKey) }
  82. set { setRetainedAssociatedObject(base, imagesKey, newValue) }
  83. }
  84. private(set) var duration: TimeInterval {
  85. get { return getAssociatedObject(base, durationKey) ?? 0.0 }
  86. set { setRetainedAssociatedObject(base, durationKey, newValue) }
  87. }
  88. var size: CGSize {
  89. // Prefer to use pixel size of the image
  90. let pixelSize = base.representations.reduce(.zero) { size, rep in
  91. CGSize(
  92. width: max(size.width, CGFloat(rep.pixelsWide)),
  93. height: max(size.height, CGFloat(rep.pixelsHigh))
  94. )
  95. }
  96. // If the pixel size is zero (SVG or PDF, for example), use the size of the image.
  97. return pixelSize == .zero ? base.representations.reduce(.zero) { size, rep in
  98. CGSize(
  99. width: max(size.width, CGFloat(rep.size.width)),
  100. height: max(size.height, CGFloat(rep.size.height))
  101. )
  102. } : pixelSize
  103. }
  104. #else
  105. var cgImage: CGImage? { return base.cgImage }
  106. var scale: CGFloat { return base.scale }
  107. var images: [KFCrossPlatformImage]? { return base.images }
  108. var duration: TimeInterval { return base.duration }
  109. var size: CGSize { return base.size }
  110. /// The source reference for the current image.
  111. public var imageSource: CGImageSource? {
  112. get {
  113. guard let frameSource = frameSource as? CGImageFrameSource else { return nil }
  114. return frameSource.imageSource
  115. }
  116. }
  117. #endif
  118. /// The custom frame source for the current image.
  119. public private(set) var frameSource: (any ImageFrameSource)? {
  120. get { return getAssociatedObject(base, imageSourceKey) }
  121. set { setRetainedAssociatedObject(base, imageSourceKey, newValue) }
  122. }
  123. /// Copies Kingfisher internal image states from `base` to a `target` image.
  124. ///
  125. /// This includes the embedded animated image data and related metadata that are used by Kingfisher for caching and
  126. /// animated image rendering. It is useful when a custom processor creates and returns a new image instance from
  127. /// an animated image in `.image` branch.
  128. ///
  129. /// - Important: This method does not make the `target` image animated by itself. It only propagates Kingfisher's
  130. /// internal metadata so the cache can preserve the original animated bytes when possible.
  131. ///
  132. /// - Parameter target: The target image to which the internal states will be copied.
  133. public func copyKingfisherState(to target: KFCrossPlatformImage) {
  134. target.kf.animatedImageData = animatedImageData
  135. target.kf.imageFrameCount = imageFrameCount
  136. target.kf.frameSource = frameSource
  137. target.kf.imageCreatingOptions = imageCreatingOptions
  138. #if os(macOS)
  139. target.kf.images = images
  140. target.kf.duration = duration
  141. #endif
  142. }
  143. // Bitmap memory cost with bytes.
  144. var cost: Int {
  145. let pixel = Int(size.width * size.height * scale * scale)
  146. guard let cgImage = cgImage else {
  147. return pixel * 4
  148. }
  149. let bytesPerPixel = cgImage.bitsPerPixel / 8
  150. guard let imageCount = images?.count else {
  151. return pixel * bytesPerPixel
  152. }
  153. return pixel * bytesPerPixel * imageCount
  154. }
  155. }
  156. // MARK: - Image Conversion
  157. extension KingfisherWrapper where Base: KFCrossPlatformImage {
  158. #if os(macOS)
  159. static func image(cgImage: CGImage, scale: CGFloat, refImage: KFCrossPlatformImage?) -> KFCrossPlatformImage {
  160. return KFCrossPlatformImage(cgImage: cgImage, size: .zero)
  161. }
  162. /// The normalized image. On macOS, this getter returns the image itself without performing any additional operations.
  163. public var normalized: KFCrossPlatformImage { return base }
  164. #else
  165. /// Create an image from a given `CGImage` with specified scale and orientation, tailored for `refImage`. This
  166. /// method signature is designed for compatibility with macOS versions.
  167. ///
  168. /// - Parameters:
  169. /// - cgImage: The `CGImage` which is used to create the `UIImage` object.
  170. /// - scale: The scale.
  171. /// - refImage: The ref image which is used to determine the image orientation.
  172. /// - Returns: The created image object.
  173. static func image(cgImage: CGImage, scale: CGFloat, refImage: KFCrossPlatformImage?) -> KFCrossPlatformImage {
  174. return KFCrossPlatformImage(cgImage: cgImage, scale: scale, orientation: refImage?.imageOrientation ?? .up)
  175. }
  176. /// The normalized image for the current `base` image.
  177. ///
  178. /// This method attempts to redraw the image, taking orientation and scale into account.
  179. public var normalized: KFCrossPlatformImage {
  180. // prevent animated image (GIF) lose it's images
  181. guard images == nil else { return base.copy() as! KFCrossPlatformImage }
  182. // No need to do anything if already up
  183. guard base.imageOrientation != .up else { return base.copy() as! KFCrossPlatformImage }
  184. return draw(to: size, inverting: true, refImage: KFCrossPlatformImage()) {
  185. fixOrientation(in: $0)
  186. return true
  187. }
  188. }
  189. func fixOrientation(in context: CGContext) {
  190. guard let cgImage else { return }
  191. var transform = CGAffineTransform.identity
  192. let orientation = base.imageOrientation
  193. switch orientation {
  194. case .down, .downMirrored:
  195. transform = transform.translatedBy(x: size.width, y: size.height)
  196. transform = transform.rotated(by: .pi)
  197. case .left, .leftMirrored:
  198. transform = transform.translatedBy(x: size.width, y: 0)
  199. transform = transform.rotated(by: .pi / 2.0)
  200. case .right, .rightMirrored:
  201. transform = transform.translatedBy(x: 0, y: size.height)
  202. transform = transform.rotated(by: .pi / -2.0)
  203. case .up, .upMirrored:
  204. break
  205. @unknown default:
  206. break
  207. }
  208. // Flip image one more time if needed for mirrored images. This is to prevent the flipped image.
  209. switch orientation {
  210. case .upMirrored, .downMirrored:
  211. transform = transform.translatedBy(x: size.width, y: 0)
  212. transform = transform.scaledBy(x: -1, y: 1)
  213. case .leftMirrored, .rightMirrored:
  214. transform = transform.translatedBy(x: size.height, y: 0)
  215. transform = transform.scaledBy(x: -1, y: 1)
  216. case .up, .down, .left, .right:
  217. break
  218. @unknown default:
  219. break
  220. }
  221. context.concatenate(transform)
  222. switch orientation {
  223. case .left, .leftMirrored, .right, .rightMirrored:
  224. context.draw(cgImage, in: CGRect(x: 0, y: 0, width: size.height, height: size.width))
  225. default:
  226. context.draw(cgImage, in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
  227. }
  228. }
  229. #endif
  230. }
  231. // MARK: - Image Representation
  232. extension KingfisherWrapper where Base: KFCrossPlatformImage {
  233. /// Returns a data object that contains the specified image in PNG format.
  234. ///
  235. /// - Returns: PNG data of image.
  236. public func pngRepresentation() -> Data? {
  237. #if os(macOS)
  238. guard let cgImage = cgImage else {
  239. return nil
  240. }
  241. let rep = NSBitmapImageRep(cgImage: cgImage)
  242. return rep.representation(using: .png, properties: [:])
  243. #else
  244. return base.pngData()
  245. #endif
  246. }
  247. /// Returns a data object that contains the specified image in JPEG format.
  248. ///
  249. /// - Parameter compressionQuality: The compression quality when converting image to JPEG data.
  250. /// - Returns: JPEG data of image.
  251. public func jpegRepresentation(compressionQuality: CGFloat) -> Data? {
  252. #if os(macOS)
  253. guard let cgImage = cgImage else {
  254. return nil
  255. }
  256. let rep = NSBitmapImageRep(cgImage: cgImage)
  257. return rep.representation(using:.jpeg, properties: [.compressionFactor: compressionQuality])
  258. #else
  259. return base.jpegData(compressionQuality: compressionQuality)
  260. #endif
  261. }
  262. /// Returns GIF representation of `base` image.
  263. ///
  264. /// - Returns: Original GIF data of image.
  265. public func gifRepresentation() -> Data? {
  266. return animatedImageData
  267. }
  268. /// Returns a data representation for the `base` image with the specified `format`.
  269. ///
  270. /// - Parameters:
  271. /// - format: The desired format for the output data. If set to `unknown`, the `base` image will be
  272. /// converted to PNG representation.
  273. /// - compressionQuality: The compression quality when converting the image to a lossy format data.
  274. ///
  275. /// - Returns: The resulting data representation.
  276. public func data(format: ImageFormat, compressionQuality: CGFloat = 1.0) -> Data? {
  277. return autoreleasepool { () -> Data? in
  278. let data: Data?
  279. switch format {
  280. case .PNG: data = pngRepresentation()
  281. case .JPEG: data = jpegRepresentation(compressionQuality: compressionQuality)
  282. case .GIF: data = gifRepresentation()
  283. case .unknown: data = normalized.kf.pngRepresentation()
  284. }
  285. return data
  286. }
  287. }
  288. }
  289. // MARK: - Creating Images
  290. extension KingfisherWrapper where Base: KFCrossPlatformImage {
  291. /// Creates an animated image from provided data and options.
  292. ///
  293. /// - Parameters:
  294. /// - data: The data containing the animated image.
  295. /// - options: Options to be used when creating the animated image.
  296. /// - Returns: An `Image` object representing the animated image. It's structured as an array of image frames,
  297. /// each with a specific duration. Returns `nil` if any issues occur during animated image creation.
  298. ///
  299. /// - Note: Currently, only GIF data is supported.
  300. public static func animatedImage(data: Data, options: ImageCreatingOptions) -> KFCrossPlatformImage? {
  301. #if os(visionOS)
  302. let info: [String: Any] = [
  303. kCGImageSourceShouldCache as String: true,
  304. kCGImageSourceTypeIdentifierHint as String: UTType.gif.identifier
  305. ]
  306. #else
  307. let info: [String: Any] = [
  308. kCGImageSourceShouldCache as String: true,
  309. kCGImageSourceTypeIdentifierHint as String: kUTTypeGIF
  310. ]
  311. #endif
  312. guard let imageSource = CGImageSourceCreateWithData(data as CFData, info as CFDictionary) else {
  313. return nil
  314. }
  315. let frameSource = CGImageFrameSource(data: data, imageSource: imageSource, options: info)
  316. #if os(macOS)
  317. let baseImage = KFCrossPlatformImage(data: data)
  318. #else
  319. let baseImage = KFCrossPlatformImage(data: data, scale: options.scale)
  320. #endif
  321. return animatedImage(source: frameSource, options: options, baseImage: baseImage)
  322. }
  323. /// Creates an animated image from a given frame source.
  324. ///
  325. /// - Parameters:
  326. /// - source: The frame source from which to create the animated image.
  327. /// - options: Options to be used during animated image creation.
  328. /// - baseImage: An optional image object to serve as the key frame of the animated image. If `nil`, the first
  329. /// frame of the `source` will be used.
  330. /// - Returns: An `Image` object representing the animated image. It consists of an array of image frames, each with a
  331. /// specific duration. Returns `nil` if any issues arise during animated image creation.
  332. public static func animatedImage(source: any ImageFrameSource, options: ImageCreatingOptions, baseImage: KFCrossPlatformImage? = nil) -> KFCrossPlatformImage? {
  333. #if os(macOS)
  334. guard let animatedImage = GIFAnimatedImage(from: source, options: options) else {
  335. return nil
  336. }
  337. var image: KFCrossPlatformImage?
  338. if options.onlyFirstFrame {
  339. image = animatedImage.images.first
  340. } else {
  341. if let baseImage = baseImage {
  342. image = baseImage
  343. } else {
  344. image = animatedImage.images.first
  345. }
  346. var kf = image?.kf
  347. kf?.images = animatedImage.images
  348. kf?.duration = animatedImage.duration
  349. }
  350. image?.kf.animatedImageData = source.data
  351. image?.kf.imageFrameCount = source.frameCount
  352. image?.kf.frameSource = source
  353. image?.kf.imageCreatingOptions = options
  354. return image
  355. #else
  356. var image: KFCrossPlatformImage?
  357. if options.preloadAll || options.onlyFirstFrame {
  358. // Use `images` image if you want to preload all animated data
  359. guard let animatedImage = GIFAnimatedImage(from: source, options: options) else {
  360. return nil
  361. }
  362. if options.onlyFirstFrame {
  363. image = animatedImage.images.first
  364. } else {
  365. let duration = options.duration <= 0.0 ? animatedImage.duration : options.duration
  366. image = .animatedImage(with: animatedImage.images, duration: duration)
  367. }
  368. image?.kf.animatedImageData = source.data
  369. } else {
  370. if let baseImage = baseImage {
  371. image = baseImage
  372. } else {
  373. guard let firstFrame = source.frame(at: 0) else {
  374. return nil
  375. }
  376. image = KFCrossPlatformImage(cgImage: firstFrame, scale: options.scale, orientation: .up)
  377. }
  378. var kf = image?.kf
  379. kf?.frameSource = source
  380. kf?.animatedImageData = source.data
  381. }
  382. image?.kf.imageFrameCount = source.frameCount
  383. image?.kf.imageCreatingOptions = options
  384. return image
  385. #endif
  386. }
  387. /// Creates an image from provided data and options. Supported formats include `.JPEG`, `.PNG`, or `.GIF`. For
  388. /// other image formats, the system's image initializer will be used. If no image object can be created from the
  389. /// given `data`, `nil` will be returned.
  390. ///
  391. /// - Parameters:
  392. /// - data: The data representing the image.
  393. /// - options: Options to be used when creating the image.
  394. /// - Returns: An `Image` object representing the image if successfully created. If the `data` is invalid or
  395. /// unsupported, `nil` will be returned.
  396. public static func image(data: Data, options: ImageCreatingOptions) -> KFCrossPlatformImage? {
  397. var image: KFCrossPlatformImage?
  398. switch data.kf.imageFormat {
  399. case .JPEG:
  400. image = KFCrossPlatformImage(data: data, scale: options.scale)
  401. case .PNG:
  402. image = KFCrossPlatformImage(data: data, scale: options.scale)
  403. case .GIF:
  404. image = KingfisherWrapper.animatedImage(data: data, options: options)
  405. case .unknown:
  406. image = KFCrossPlatformImage(data: data, scale: options.scale)
  407. }
  408. return image
  409. }
  410. /// Creates a downsampled image from the given data to a specified size and scale.
  411. ///
  412. /// - Parameters:
  413. /// - data: The image data containing a JPEG or PNG image.
  414. /// - pointSize: The target size in points to which the image should be downsampled.
  415. /// - scale: The scale of the resulting image.
  416. /// - Returns: A downsampled `Image` object adhering to the specified conditions.
  417. ///
  418. /// Unlike image `resize` methods, downsampling does not render the original input image in pixel format.
  419. /// Instead, it downsamples directly from the image data, making it more memory-efficient and friendly. Whenever
  420. /// possible, consider using downsampling.
  421. ///
  422. /// > Important: The `pointSize` should be smaller than the size of the input image. If it is larger than the original image
  423. /// > size, the resulting image will have the same dimensions as the input without downsampling.
  424. public static func downsampledImage(data: Data, to pointSize: CGSize, scale: CGFloat) -> KFCrossPlatformImage? {
  425. let imageSourceOptions = [kCGImageSourceShouldCache: false] as CFDictionary
  426. guard let imageSource = CGImageSourceCreateWithData(data as CFData, imageSourceOptions) else {
  427. return nil
  428. }
  429. let maxDimensionInPixels = max(pointSize.width, pointSize.height) * scale
  430. let downsampleOptions: [CFString : Any] = [
  431. kCGImageSourceCreateThumbnailFromImageAlways: true,
  432. kCGImageSourceShouldCacheImmediately: true,
  433. kCGImageSourceCreateThumbnailWithTransform: true,
  434. kCGImageSourceThumbnailMaxPixelSize: maxDimensionInPixels
  435. ]
  436. guard let downsampledImage = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, downsampleOptions as CFDictionary) else {
  437. return nil
  438. }
  439. return KingfisherWrapper.image(cgImage: downsampledImage, scale: scale, refImage: nil)
  440. }
  441. }