Image.swift 18 KB

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