Image.swift 18 KB

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