Image.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  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. private var imagesKey: Void?
  29. private var durationKey: Void?
  30. #else
  31. import UIKit
  32. import MobileCoreServices
  33. private var imageSourceKey: Void?
  34. #endif
  35. #if !os(watchOS)
  36. import CoreImage
  37. #endif
  38. import CoreGraphics
  39. import ImageIO
  40. private var animatedImageDataKey: Void?
  41. // MARK: - Image Properties
  42. extension KingfisherWrapper where Base: KFCrossPlatformImage {
  43. private(set) var animatedImageData: Data? {
  44. get { return getAssociatedObject(base, &animatedImageDataKey) }
  45. set { setRetainedAssociatedObject(base, &animatedImageDataKey, newValue) }
  46. }
  47. #if os(macOS)
  48. var cgImage: CGImage? {
  49. return base.cgImage(forProposedRect: nil, context: nil, hints: nil)
  50. }
  51. var scale: CGFloat {
  52. return 1.0
  53. }
  54. private(set) var images: [KFCrossPlatformImage]? {
  55. get { return getAssociatedObject(base, &imagesKey) }
  56. set { setRetainedAssociatedObject(base, &imagesKey, newValue) }
  57. }
  58. private(set) var duration: TimeInterval {
  59. get { return getAssociatedObject(base, &durationKey) ?? 0.0 }
  60. set { setRetainedAssociatedObject(base, &durationKey, newValue) }
  61. }
  62. var size: CGSize {
  63. return base.representations.reduce(.zero) { size, rep in
  64. let width = max(size.width, CGFloat(rep.pixelsWide))
  65. let height = max(size.height, CGFloat(rep.pixelsHigh))
  66. return CGSize(width: width, height: height)
  67. }
  68. }
  69. #else
  70. var cgImage: CGImage? { return base.cgImage }
  71. var scale: CGFloat { return base.scale }
  72. var images: [KFCrossPlatformImage]? { return base.images }
  73. var duration: TimeInterval { return base.duration }
  74. var size: CGSize { return base.size }
  75. private(set) var imageSource: CGImageSource? {
  76. get { return getAssociatedObject(base, &imageSourceKey) }
  77. set { setRetainedAssociatedObject(base, &imageSourceKey, newValue) }
  78. }
  79. #endif
  80. // Bitmap memory cost with bytes.
  81. var cost: Int {
  82. let pixel = Int(size.width * size.height * scale * scale)
  83. guard let cgImage = cgImage else {
  84. return pixel * 4
  85. }
  86. return pixel * cgImage.bitsPerPixel / 8
  87. }
  88. }
  89. // MARK: - Image Conversion
  90. extension KingfisherWrapper where Base: KFCrossPlatformImage {
  91. #if os(macOS)
  92. static func image(cgImage: CGImage, scale: CGFloat, refImage: KFCrossPlatformImage?) -> KFCrossPlatformImage {
  93. return KFCrossPlatformImage(cgImage: cgImage, size: .zero)
  94. }
  95. /// Normalize the image. This getter does nothing on macOS but return the image itself.
  96. public var normalized: KFCrossPlatformImage { return base }
  97. #else
  98. /// Creating an image from a give `CGImage` at scale and orientation for refImage. The method signature is for
  99. /// compatibility of macOS version.
  100. static func image(cgImage: CGImage, scale: CGFloat, refImage: KFCrossPlatformImage?) -> KFCrossPlatformImage {
  101. return KFCrossPlatformImage(cgImage: cgImage, scale: scale, orientation: refImage?.imageOrientation ?? .up)
  102. }
  103. /// Returns normalized image for current `base` image.
  104. /// This method will try to redraw an image with orientation and scale considered.
  105. public var normalized: KFCrossPlatformImage {
  106. // prevent animated image (GIF) lose it's images
  107. guard images == nil else { return base.copy() as! KFCrossPlatformImage }
  108. // No need to do anything if already up
  109. guard base.imageOrientation != .up else { return base.copy() as! KFCrossPlatformImage }
  110. return draw(to: size, inverting: true, refImage: KFCrossPlatformImage()) {
  111. fixOrientation(in: $0)
  112. }
  113. }
  114. func fixOrientation(in context: CGContext) {
  115. var transform = CGAffineTransform.identity
  116. let orientation = base.imageOrientation
  117. switch orientation {
  118. case .down, .downMirrored:
  119. transform = transform.translatedBy(x: size.width, y: size.height)
  120. transform = transform.rotated(by: .pi)
  121. case .left, .leftMirrored:
  122. transform = transform.translatedBy(x: size.width, y: 0)
  123. transform = transform.rotated(by: .pi / 2.0)
  124. case .right, .rightMirrored:
  125. transform = transform.translatedBy(x: 0, y: size.height)
  126. transform = transform.rotated(by: .pi / -2.0)
  127. case .up, .upMirrored:
  128. break
  129. #if compiler(>=5)
  130. @unknown default:
  131. break
  132. #endif
  133. }
  134. //Flip image one more time if needed to, this is to prevent flipped image
  135. switch orientation {
  136. case .upMirrored, .downMirrored:
  137. transform = transform.translatedBy(x: size.width, y: 0)
  138. transform = transform.scaledBy(x: -1, y: 1)
  139. case .leftMirrored, .rightMirrored:
  140. transform = transform.translatedBy(x: size.height, y: 0)
  141. transform = transform.scaledBy(x: -1, y: 1)
  142. case .up, .down, .left, .right:
  143. break
  144. #if compiler(>=5)
  145. @unknown default:
  146. break
  147. #endif
  148. }
  149. context.concatenate(transform)
  150. switch orientation {
  151. case .left, .leftMirrored, .right, .rightMirrored:
  152. context.draw(cgImage!, in: CGRect(x: 0, y: 0, width: size.height, height: size.width))
  153. default:
  154. context.draw(cgImage!, in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
  155. }
  156. }
  157. #endif
  158. }
  159. // MARK: - Image Representation
  160. extension KingfisherWrapper where Base: KFCrossPlatformImage {
  161. /// Returns PNG representation of `base` image.
  162. ///
  163. /// - Returns: PNG data of image.
  164. public func pngRepresentation() -> Data? {
  165. #if os(macOS)
  166. guard let cgImage = cgImage else {
  167. return nil
  168. }
  169. let rep = NSBitmapImageRep(cgImage: cgImage)
  170. return rep.representation(using: .png, properties: [:])
  171. #else
  172. #if swift(>=4.2)
  173. return base.pngData()
  174. #else
  175. return UIImagePNGRepresentation(base)
  176. #endif
  177. #endif
  178. }
  179. /// Returns JPEG representation of `base` image.
  180. ///
  181. /// - Parameter compressionQuality: The compression quality when converting image to JPEG data.
  182. /// - Returns: JPEG data of image.
  183. public func jpegRepresentation(compressionQuality: CGFloat) -> Data? {
  184. #if os(macOS)
  185. guard let cgImage = cgImage else {
  186. return nil
  187. }
  188. let rep = NSBitmapImageRep(cgImage: cgImage)
  189. return rep.representation(using:.jpeg, properties: [.compressionFactor: compressionQuality])
  190. #else
  191. #if swift(>=4.2)
  192. return base.jpegData(compressionQuality: compressionQuality)
  193. #else
  194. return UIImageJPEGRepresentation(base, compressionQuality)
  195. #endif
  196. #endif
  197. }
  198. /// Returns GIF representation of `base` image.
  199. ///
  200. /// - Returns: Original GIF data of image.
  201. public func gifRepresentation() -> Data? {
  202. return animatedImageData
  203. }
  204. /// Returns a data representation for `base` image, with the `format` as the format indicator.
  205. ///
  206. /// - Parameter format: The format in which the output data should be. If `unknown`, the `base` image will be
  207. /// converted in the PNG representation.
  208. /// - Returns: The output data representing.
  209. public func data(format: ImageFormat) -> Data? {
  210. return autoreleasepool { () -> Data? in
  211. let data: Data?
  212. switch format {
  213. case .PNG: data = pngRepresentation()
  214. case .JPEG: data = jpegRepresentation(compressionQuality: 1.0)
  215. case .GIF: data = gifRepresentation()
  216. case .unknown: data = normalized.kf.pngRepresentation()
  217. }
  218. return data
  219. }
  220. }
  221. }
  222. // MARK: - Creating Images
  223. extension KingfisherWrapper where Base: KFCrossPlatformImage {
  224. /// Creates an animated image from a given data and options. Currently only GIF data is supported.
  225. ///
  226. /// - Parameters:
  227. /// - data: The animated image data.
  228. /// - options: Options to use when creating the animated image.
  229. /// - Returns: An `Image` object represents the animated image. It is in form of an array of image frames with a
  230. /// certain duration. `nil` if anything wrong when creating animated image.
  231. public static func animatedImage(data: Data, options: ImageCreatingOptions) -> KFCrossPlatformImage? {
  232. let info: [String: Any] = [
  233. kCGImageSourceShouldCache as String: true,
  234. kCGImageSourceTypeIdentifierHint as String: kUTTypeGIF
  235. ]
  236. guard let imageSource = CGImageSourceCreateWithData(data as CFData, info as CFDictionary) else {
  237. return nil
  238. }
  239. #if os(macOS)
  240. guard let animatedImage = GIFAnimatedImage(from: imageSource, for: info, options: options) else {
  241. return nil
  242. }
  243. var image: KFCrossPlatformImage?
  244. if options.onlyFirstFrame {
  245. image = animatedImage.images.first
  246. } else {
  247. image = KFCrossPlatformImage(data: data)
  248. var kf = image?.kf
  249. kf?.images = animatedImage.images
  250. kf?.duration = animatedImage.duration
  251. }
  252. image?.kf.animatedImageData = data
  253. return image
  254. #else
  255. var image: KFCrossPlatformImage?
  256. if options.preloadAll || options.onlyFirstFrame {
  257. // Use `images` image if you want to preload all animated data
  258. guard let animatedImage = GIFAnimatedImage(from: imageSource, for: info, options: options) else {
  259. return nil
  260. }
  261. if options.onlyFirstFrame {
  262. image = animatedImage.images.first
  263. } else {
  264. let duration = options.duration <= 0.0 ? animatedImage.duration : options.duration
  265. image = .animatedImage(with: animatedImage.images, duration: duration)
  266. }
  267. image?.kf.animatedImageData = data
  268. } else {
  269. image = KFCrossPlatformImage(data: data, scale: options.scale)
  270. var kf = image?.kf
  271. kf?.imageSource = imageSource
  272. kf?.animatedImageData = data
  273. }
  274. return image
  275. #endif
  276. }
  277. /// Creates an image from a given data and options. `.JPEG`, `.PNG` or `.GIF` is supported. For other
  278. /// image format, image initializer from system will be used. If no image object could be created from
  279. /// the given `data`, `nil` will be returned.
  280. ///
  281. /// - Parameters:
  282. /// - data: The image data representation.
  283. /// - options: Options to use when creating the image.
  284. /// - Returns: An `Image` object represents the image if created. If the `data` is invalid or not supported, `nil`
  285. /// will be returned.
  286. public static func image(data: Data, options: ImageCreatingOptions) -> KFCrossPlatformImage? {
  287. var image: KFCrossPlatformImage?
  288. switch data.kf.imageFormat {
  289. case .JPEG:
  290. image = KFCrossPlatformImage(data: data, scale: options.scale)
  291. case .PNG:
  292. image = KFCrossPlatformImage(data: data, scale: options.scale)
  293. case .GIF:
  294. image = KingfisherWrapper.animatedImage(data: data, options: options)
  295. case .unknown:
  296. image = KFCrossPlatformImage(data: data, scale: options.scale)
  297. }
  298. return image
  299. }
  300. /// Creates a downsampled image from given data to a certain size and scale.
  301. ///
  302. /// - Parameters:
  303. /// - data: The image data contains a JPEG or PNG image.
  304. /// - pointSize: The target size in point to which the image should be downsampled.
  305. /// - scale: The scale of result image.
  306. /// - Returns: A downsampled `Image` object following the input conditions.
  307. ///
  308. /// - Note:
  309. /// Different from image `resize` methods, downsampling will not render the original
  310. /// input image in pixel format. It does downsampling from the image data, so it is much
  311. /// more memory efficient and friendly. Choose to use downsampling as possible as you can.
  312. ///
  313. /// The input size should be smaller than the size of input image. If it is larger than the
  314. /// original image size, the result image will be the same size of input without downsampling.
  315. public static func downsampledImage(data: Data, to pointSize: CGSize, scale: CGFloat) -> KFCrossPlatformImage? {
  316. let imageSourceOptions = [kCGImageSourceShouldCache: false] as CFDictionary
  317. guard let imageSource = CGImageSourceCreateWithData(data as CFData, imageSourceOptions) else {
  318. return nil
  319. }
  320. let maxDimensionInPixels = max(pointSize.width, pointSize.height) * scale
  321. let downsampleOptions = [
  322. kCGImageSourceCreateThumbnailFromImageAlways: true,
  323. kCGImageSourceShouldCacheImmediately: true,
  324. kCGImageSourceCreateThumbnailWithTransform: true,
  325. kCGImageSourceThumbnailMaxPixelSize: maxDimensionInPixels] as CFDictionary
  326. guard let downsampledImage = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, downsampleOptions) else {
  327. return nil
  328. }
  329. return KingfisherWrapper.image(cgImage: downsampledImage, scale: scale, refImage: nil)
  330. }
  331. }