Image.swift 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  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. // Bitmap memory cost with bytes.
  124. var cost: Int {
  125. let pixel = Int(size.width * size.height * scale * scale)
  126. guard let cgImage = cgImage else {
  127. return pixel * 4
  128. }
  129. let bytesPerPixel = cgImage.bitsPerPixel / 8
  130. guard let imageCount = images?.count else {
  131. return pixel * bytesPerPixel
  132. }
  133. return pixel * bytesPerPixel * imageCount
  134. }
  135. }
  136. // MARK: - Image Conversion
  137. extension KingfisherWrapper where Base: KFCrossPlatformImage {
  138. #if os(macOS)
  139. static func image(cgImage: CGImage, scale: CGFloat, refImage: KFCrossPlatformImage?) -> KFCrossPlatformImage {
  140. return KFCrossPlatformImage(cgImage: cgImage, size: .zero)
  141. }
  142. /// The normalized image. On macOS, this getter returns the image itself without performing any additional operations.
  143. public var normalized: KFCrossPlatformImage { return base }
  144. #else
  145. /// Create an image from a given `CGImage` with specified scale and orientation, tailored for `refImage`. This
  146. /// method signature is designed for compatibility with macOS versions.
  147. ///
  148. /// - Parameters:
  149. /// - cgImage: The `CGImage` which is used to create the `UIImage` object.
  150. /// - scale: The scale.
  151. /// - refImage: The ref image which is used to determine the image orientation.
  152. /// - Returns: The created image object.
  153. static func image(cgImage: CGImage, scale: CGFloat, refImage: KFCrossPlatformImage?) -> KFCrossPlatformImage {
  154. return KFCrossPlatformImage(cgImage: cgImage, scale: scale, orientation: refImage?.imageOrientation ?? .up)
  155. }
  156. /// The normalized image for the current `base` image.
  157. ///
  158. /// This method attempts to redraw the image, taking orientation and scale into account.
  159. public var normalized: KFCrossPlatformImage {
  160. // prevent animated image (GIF) lose it's images
  161. guard images == nil else { return base.copy() as! KFCrossPlatformImage }
  162. // No need to do anything if already up
  163. guard base.imageOrientation != .up else { return base.copy() as! KFCrossPlatformImage }
  164. return draw(to: size, inverting: true, refImage: KFCrossPlatformImage()) {
  165. fixOrientation(in: $0)
  166. return true
  167. }
  168. }
  169. func fixOrientation(in context: CGContext) {
  170. guard let cgImage else { return }
  171. var transform = CGAffineTransform.identity
  172. let orientation = base.imageOrientation
  173. switch orientation {
  174. case .down, .downMirrored:
  175. transform = transform.translatedBy(x: size.width, y: size.height)
  176. transform = transform.rotated(by: .pi)
  177. case .left, .leftMirrored:
  178. transform = transform.translatedBy(x: size.width, y: 0)
  179. transform = transform.rotated(by: .pi / 2.0)
  180. case .right, .rightMirrored:
  181. transform = transform.translatedBy(x: 0, y: size.height)
  182. transform = transform.rotated(by: .pi / -2.0)
  183. case .up, .upMirrored:
  184. break
  185. @unknown default:
  186. break
  187. }
  188. // Flip image one more time if needed for mirrored images. This is to prevent the flipped image.
  189. switch orientation {
  190. case .upMirrored, .downMirrored:
  191. transform = transform.translatedBy(x: size.width, y: 0)
  192. transform = transform.scaledBy(x: -1, y: 1)
  193. case .leftMirrored, .rightMirrored:
  194. transform = transform.translatedBy(x: size.height, y: 0)
  195. transform = transform.scaledBy(x: -1, y: 1)
  196. case .up, .down, .left, .right:
  197. break
  198. @unknown default:
  199. break
  200. }
  201. context.concatenate(transform)
  202. switch orientation {
  203. case .left, .leftMirrored, .right, .rightMirrored:
  204. context.draw(cgImage, in: CGRect(x: 0, y: 0, width: size.height, height: size.width))
  205. default:
  206. context.draw(cgImage, in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
  207. }
  208. }
  209. #endif
  210. }
  211. // MARK: - Image Representation
  212. extension KingfisherWrapper where Base: KFCrossPlatformImage {
  213. /// Returns a data object that contains the specified image in PNG format.
  214. ///
  215. /// - Returns: PNG data of image.
  216. public func pngRepresentation() -> Data? {
  217. #if os(macOS)
  218. guard let cgImage = cgImage else {
  219. return nil
  220. }
  221. let rep = NSBitmapImageRep(cgImage: cgImage)
  222. return rep.representation(using: .png, properties: [:])
  223. #else
  224. return base.pngData()
  225. #endif
  226. }
  227. /// Returns a data object that contains the specified image in JPEG format.
  228. ///
  229. /// - Parameter compressionQuality: The compression quality when converting image to JPEG data.
  230. /// - Returns: JPEG data of image.
  231. public func jpegRepresentation(compressionQuality: CGFloat) -> Data? {
  232. #if os(macOS)
  233. guard let cgImage = cgImage else {
  234. return nil
  235. }
  236. let rep = NSBitmapImageRep(cgImage: cgImage)
  237. return rep.representation(using:.jpeg, properties: [.compressionFactor: compressionQuality])
  238. #else
  239. return base.jpegData(compressionQuality: compressionQuality)
  240. #endif
  241. }
  242. /// Returns GIF representation of `base` image.
  243. ///
  244. /// - Returns: Original GIF data of image.
  245. public func gifRepresentation() -> Data? {
  246. return animatedImageData
  247. }
  248. /// Returns a data representation for the `base` image with the specified `format`.
  249. ///
  250. /// - Parameters:
  251. /// - format: The desired format for the output data. If set to `unknown`, the `base` image will be
  252. /// converted to PNG representation.
  253. /// - compressionQuality: The compression quality when converting the image to a lossy format data.
  254. ///
  255. /// - Returns: The resulting data representation.
  256. public func data(format: ImageFormat, compressionQuality: CGFloat = 1.0) -> Data? {
  257. return autoreleasepool { () -> Data? in
  258. let data: Data?
  259. switch format {
  260. case .PNG: data = pngRepresentation()
  261. case .JPEG: data = jpegRepresentation(compressionQuality: compressionQuality)
  262. case .GIF: data = gifRepresentation()
  263. case .unknown: data = normalized.kf.pngRepresentation()
  264. }
  265. return data
  266. }
  267. }
  268. }
  269. // MARK: - Creating Images
  270. extension KingfisherWrapper where Base: KFCrossPlatformImage {
  271. /// Creates an animated image from provided data and options.
  272. ///
  273. /// - Parameters:
  274. /// - data: The data containing the animated image.
  275. /// - options: Options to be used when creating the animated image.
  276. /// - Returns: An `Image` object representing the animated image. It's structured as an array of image frames,
  277. /// each with a specific duration. Returns `nil` if any issues occur during animated image creation.
  278. ///
  279. /// - Note: Currently, only GIF data is supported.
  280. public static func animatedImage(data: Data, options: ImageCreatingOptions) -> KFCrossPlatformImage? {
  281. #if os(visionOS)
  282. let info: [String: Any] = [
  283. kCGImageSourceShouldCache as String: true,
  284. kCGImageSourceTypeIdentifierHint as String: UTType.gif.identifier
  285. ]
  286. #else
  287. let info: [String: Any] = [
  288. kCGImageSourceShouldCache as String: true,
  289. kCGImageSourceTypeIdentifierHint as String: kUTTypeGIF
  290. ]
  291. #endif
  292. guard let imageSource = CGImageSourceCreateWithData(data as CFData, info as CFDictionary) else {
  293. return nil
  294. }
  295. let frameSource = CGImageFrameSource(data: data, imageSource: imageSource, options: info)
  296. #if os(macOS)
  297. let baseImage = KFCrossPlatformImage(data: data)
  298. #else
  299. let baseImage = KFCrossPlatformImage(data: data, scale: options.scale)
  300. #endif
  301. return animatedImage(source: frameSource, options: options, baseImage: baseImage)
  302. }
  303. /// Creates an animated image from a given frame source.
  304. ///
  305. /// - Parameters:
  306. /// - source: The frame source from which to create the animated image.
  307. /// - options: Options to be used during animated image creation.
  308. /// - baseImage: An optional image object to serve as the key frame of the animated image. If `nil`, the first
  309. /// frame of the `source` will be used.
  310. /// - Returns: An `Image` object representing the animated image. It consists of an array of image frames, each with a
  311. /// specific duration. Returns `nil` if any issues arise during animated image creation.
  312. public static func animatedImage(source: any ImageFrameSource, options: ImageCreatingOptions, baseImage: KFCrossPlatformImage? = nil) -> KFCrossPlatformImage? {
  313. #if os(macOS)
  314. guard let animatedImage = GIFAnimatedImage(from: source, options: options) else {
  315. return nil
  316. }
  317. var image: KFCrossPlatformImage?
  318. if options.onlyFirstFrame {
  319. image = animatedImage.images.first
  320. } else {
  321. if let baseImage = baseImage {
  322. image = baseImage
  323. } else {
  324. image = animatedImage.images.first
  325. }
  326. var kf = image?.kf
  327. kf?.images = animatedImage.images
  328. kf?.duration = animatedImage.duration
  329. }
  330. image?.kf.animatedImageData = source.data
  331. image?.kf.imageFrameCount = source.frameCount
  332. image?.kf.frameSource = source
  333. image?.kf.imageCreatingOptions = options
  334. return image
  335. #else
  336. var image: KFCrossPlatformImage?
  337. if options.preloadAll || options.onlyFirstFrame {
  338. // Use `images` image if you want to preload all animated data
  339. guard let animatedImage = GIFAnimatedImage(from: source, options: options) else {
  340. return nil
  341. }
  342. if options.onlyFirstFrame {
  343. image = animatedImage.images.first
  344. } else {
  345. let duration = options.duration <= 0.0 ? animatedImage.duration : options.duration
  346. image = .animatedImage(with: animatedImage.images, duration: duration)
  347. }
  348. image?.kf.animatedImageData = source.data
  349. } else {
  350. if let baseImage = baseImage {
  351. image = baseImage
  352. } else {
  353. guard let firstFrame = source.frame(at: 0) else {
  354. return nil
  355. }
  356. image = KFCrossPlatformImage(cgImage: firstFrame, scale: options.scale, orientation: .up)
  357. }
  358. var kf = image?.kf
  359. kf?.frameSource = source
  360. kf?.animatedImageData = source.data
  361. }
  362. image?.kf.imageFrameCount = source.frameCount
  363. image?.kf.imageCreatingOptions = options
  364. return image
  365. #endif
  366. }
  367. /// Creates an image from provided data and options. Supported formats include `.JPEG`, `.PNG`, or `.GIF`. For
  368. /// other image formats, the system's image initializer will be used. If no image object can be created from the
  369. /// given `data`, `nil` will be returned.
  370. ///
  371. /// - Parameters:
  372. /// - data: The data representing the image.
  373. /// - options: Options to be used when creating the image.
  374. /// - Returns: An `Image` object representing the image if successfully created. If the `data` is invalid or
  375. /// unsupported, `nil` will be returned.
  376. public static func image(data: Data, options: ImageCreatingOptions) -> KFCrossPlatformImage? {
  377. var image: KFCrossPlatformImage?
  378. switch data.kf.imageFormat {
  379. case .JPEG:
  380. image = KFCrossPlatformImage(data: data, scale: options.scale)
  381. case .PNG:
  382. image = KFCrossPlatformImage(data: data, scale: options.scale)
  383. case .GIF:
  384. image = KingfisherWrapper.animatedImage(data: data, options: options)
  385. case .unknown:
  386. image = KFCrossPlatformImage(data: data, scale: options.scale)
  387. }
  388. return image
  389. }
  390. /// Creates a downsampled image from the given data to a specified size and scale.
  391. ///
  392. /// - Parameters:
  393. /// - data: The image data containing a JPEG or PNG image.
  394. /// - pointSize: The target size in points to which the image should be downsampled.
  395. /// - scale: The scale of the resulting image.
  396. /// - Returns: A downsampled `Image` object adhering to the specified conditions.
  397. ///
  398. /// Unlike image `resize` methods, downsampling does not render the original input image in pixel format.
  399. /// Instead, it downsamples directly from the image data, making it more memory-efficient and friendly. Whenever
  400. /// possible, consider using downsampling.
  401. ///
  402. /// > Important: The `pointSize` should be smaller than the size of the input image. If it is larger than the original image
  403. /// > size, the resulting image will have the same dimensions as the input without downsampling.
  404. public static func downsampledImage(data: Data, to pointSize: CGSize, scale: CGFloat) -> KFCrossPlatformImage? {
  405. let imageSourceOptions = [kCGImageSourceShouldCache: false] as CFDictionary
  406. guard let imageSource = CGImageSourceCreateWithData(data as CFData, imageSourceOptions) else {
  407. return nil
  408. }
  409. let maxDimensionInPixels = max(pointSize.width, pointSize.height) * scale
  410. let downsampleOptions: [CFString : Any] = [
  411. kCGImageSourceCreateThumbnailFromImageAlways: true,
  412. kCGImageSourceShouldCacheImmediately: true,
  413. kCGImageSourceCreateThumbnailWithTransform: true,
  414. kCGImageSourceThumbnailMaxPixelSize: maxDimensionInPixels
  415. ]
  416. guard let downsampledImage = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, downsampleOptions as CFDictionary) else {
  417. return nil
  418. }
  419. return KingfisherWrapper.image(cgImage: downsampledImage, scale: scale, refImage: nil)
  420. }
  421. }