Image.swift 18 KB

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