You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

377 lines
15 KiB

  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. return true
  113. }
  114. }
  115. func fixOrientation(in context: CGContext) {
  116. var transform = CGAffineTransform.identity
  117. let orientation = base.imageOrientation
  118. switch orientation {
  119. case .down, .downMirrored:
  120. transform = transform.translatedBy(x: size.width, y: size.height)
  121. transform = transform.rotated(by: .pi)
  122. case .left, .leftMirrored:
  123. transform = transform.translatedBy(x: size.width, y: 0)
  124. transform = transform.rotated(by: .pi / 2.0)
  125. case .right, .rightMirrored:
  126. transform = transform.translatedBy(x: 0, y: size.height)
  127. transform = transform.rotated(by: .pi / -2.0)
  128. case .up, .upMirrored:
  129. break
  130. #if compiler(>=5)
  131. @unknown default:
  132. break
  133. #endif
  134. }
  135. //Flip image one more time if needed to, this is to prevent flipped image
  136. switch orientation {
  137. case .upMirrored, .downMirrored:
  138. transform = transform.translatedBy(x: size.width, y: 0)
  139. transform = transform.scaledBy(x: -1, y: 1)
  140. case .leftMirrored, .rightMirrored:
  141. transform = transform.translatedBy(x: size.height, y: 0)
  142. transform = transform.scaledBy(x: -1, y: 1)
  143. case .up, .down, .left, .right:
  144. break
  145. #if compiler(>=5)
  146. @unknown default:
  147. break
  148. #endif
  149. }
  150. context.concatenate(transform)
  151. switch orientation {
  152. case .left, .leftMirrored, .right, .rightMirrored:
  153. context.draw(cgImage!, in: CGRect(x: 0, y: 0, width: size.height, height: size.width))
  154. default:
  155. context.draw(cgImage!, in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
  156. }
  157. }
  158. #endif
  159. }
  160. // MARK: - Image Representation
  161. extension KingfisherWrapper where Base: KFCrossPlatformImage {
  162. /// Returns PNG representation of `base` image.
  163. ///
  164. /// - Returns: PNG data of image.
  165. public func pngRepresentation() -> Data? {
  166. #if os(macOS)
  167. guard let cgImage = cgImage else {
  168. return nil
  169. }
  170. let rep = NSBitmapImageRep(cgImage: cgImage)
  171. return rep.representation(using: .png, properties: [:])
  172. #else
  173. #if swift(>=4.2)
  174. return base.pngData()
  175. #else
  176. return UIImagePNGRepresentation(base)
  177. #endif
  178. #endif
  179. }
  180. /// Returns JPEG representation of `base` image.
  181. ///
  182. /// - Parameter compressionQuality: The compression quality when converting image to JPEG data.
  183. /// - Returns: JPEG data of image.
  184. public func jpegRepresentation(compressionQuality: CGFloat) -> Data? {
  185. #if os(macOS)
  186. guard let cgImage = cgImage else {
  187. return nil
  188. }
  189. let rep = NSBitmapImageRep(cgImage: cgImage)
  190. return rep.representation(using:.jpeg, properties: [.compressionFactor: compressionQuality])
  191. #else
  192. #if swift(>=4.2)
  193. return base.jpegData(compressionQuality: compressionQuality)
  194. #else
  195. return UIImageJPEGRepresentation(base, compressionQuality)
  196. #endif
  197. #endif
  198. }
  199. /// Returns GIF representation of `base` image.
  200. ///
  201. /// - Returns: Original GIF data of image.
  202. public func gifRepresentation() -> Data? {
  203. return animatedImageData
  204. }
  205. /// Returns a data representation for `base` image, with the `format` as the format indicator.
  206. ///
  207. /// - Parameter format: The format in which the output data should be. If `unknown`, the `base` image will be
  208. /// converted in the PNG representation.
  209. ///
  210. /// - Returns: The output data representing.
  211. /// Returns a data representation for `base` image, with the `format` as the format indicator.
  212. /// - Parameters:
  213. /// - format: The format in which the output data should be. If `unknown`, the `base` image will be
  214. /// converted in the PNG representation.
  215. /// - compressionQuality: The compression quality when converting image to a lossy format data.
  216. public func data(format: ImageFormat, compressionQuality: CGFloat = 1.0) -> Data? {
  217. return autoreleasepool { () -> Data? in
  218. let data: Data?
  219. switch format {
  220. case .PNG: data = pngRepresentation()
  221. case .JPEG: data = jpegRepresentation(compressionQuality: compressionQuality)
  222. case .GIF: data = gifRepresentation()
  223. case .unknown: data = normalized.kf.pngRepresentation()
  224. }
  225. return data
  226. }
  227. }
  228. }
  229. // MARK: - Creating Images
  230. extension KingfisherWrapper where Base: KFCrossPlatformImage {
  231. /// Creates an animated image from a given data and options. Currently only GIF data is supported.
  232. ///
  233. /// - Parameters:
  234. /// - data: The animated image data.
  235. /// - options: Options to use when creating the animated image.
  236. /// - Returns: An `Image` object represents the animated image. It is in form of an array of image frames with a
  237. /// certain duration. `nil` if anything wrong when creating animated image.
  238. public static func animatedImage(data: Data, options: ImageCreatingOptions) -> KFCrossPlatformImage? {
  239. let info: [String: Any] = [
  240. kCGImageSourceShouldCache as String: true,
  241. kCGImageSourceTypeIdentifierHint as String: kUTTypeGIF
  242. ]
  243. guard let imageSource = CGImageSourceCreateWithData(data as CFData, info as CFDictionary) else {
  244. return nil
  245. }
  246. #if os(macOS)
  247. guard let animatedImage = GIFAnimatedImage(from: imageSource, for: info, options: options) else {
  248. return nil
  249. }
  250. var image: KFCrossPlatformImage?
  251. if options.onlyFirstFrame {
  252. image = animatedImage.images.first
  253. } else {
  254. image = KFCrossPlatformImage(data: data)
  255. var kf = image?.kf
  256. kf?.images = animatedImage.images
  257. kf?.duration = animatedImage.duration
  258. }
  259. image?.kf.animatedImageData = data
  260. return image
  261. #else
  262. var image: KFCrossPlatformImage?
  263. if options.preloadAll || options.onlyFirstFrame {
  264. // Use `images` image if you want to preload all animated data
  265. guard let animatedImage = GIFAnimatedImage(from: imageSource, for: info, options: options) else {
  266. return nil
  267. }
  268. if options.onlyFirstFrame {
  269. image = animatedImage.images.first
  270. } else {
  271. let duration = options.duration <= 0.0 ? animatedImage.duration : options.duration
  272. image = .animatedImage(with: animatedImage.images, duration: duration)
  273. }
  274. image?.kf.animatedImageData = data
  275. } else {
  276. image = KFCrossPlatformImage(data: data, scale: options.scale)
  277. var kf = image?.kf
  278. kf?.imageSource = imageSource
  279. kf?.animatedImageData = data
  280. }
  281. return image
  282. #endif
  283. }
  284. /// Creates an image from a given data and options. `.JPEG`, `.PNG` or `.GIF` is supported. For other
  285. /// image format, image initializer from system will be used. If no image object could be created from
  286. /// the given `data`, `nil` will be returned.
  287. ///
  288. /// - Parameters:
  289. /// - data: The image data representation.
  290. /// - options: Options to use when creating the image.
  291. /// - Returns: An `Image` object represents the image if created. If the `data` is invalid or not supported, `nil`
  292. /// will be returned.
  293. public static func image(data: Data, options: ImageCreatingOptions) -> KFCrossPlatformImage? {
  294. var image: KFCrossPlatformImage?
  295. switch data.kf.imageFormat {
  296. case .JPEG:
  297. image = KFCrossPlatformImage(data: data, scale: options.scale)
  298. case .PNG:
  299. image = KFCrossPlatformImage(data: data, scale: options.scale)
  300. case .GIF:
  301. image = KingfisherWrapper.animatedImage(data: data, options: options)
  302. case .unknown:
  303. image = KFCrossPlatformImage(data: data, scale: options.scale)
  304. }
  305. return image
  306. }
  307. /// Creates a downsampled image from given data to a certain size and scale.
  308. ///
  309. /// - Parameters:
  310. /// - data: The image data contains a JPEG or PNG image.
  311. /// - pointSize: The target size in point to which the image should be downsampled.
  312. /// - scale: The scale of result image.
  313. /// - Returns: A downsampled `Image` object following the input conditions.
  314. ///
  315. /// - Note:
  316. /// Different from image `resize` methods, downsampling will not render the original
  317. /// input image in pixel format. It does downsampling from the image data, so it is much
  318. /// more memory efficient and friendly. Choose to use downsampling as possible as you can.
  319. ///
  320. /// The input size should be smaller than the size of input image. If it is larger than the
  321. /// original image size, the result image will be the same size of input without downsampling.
  322. public static func downsampledImage(data: Data, to pointSize: CGSize, scale: CGFloat) -> KFCrossPlatformImage? {
  323. let imageSourceOptions = [kCGImageSourceShouldCache: false] as CFDictionary
  324. guard let imageSource = CGImageSourceCreateWithData(data as CFData, imageSourceOptions) else {
  325. return nil
  326. }
  327. let maxDimensionInPixels = max(pointSize.width, pointSize.height) * scale
  328. let downsampleOptions = [
  329. kCGImageSourceCreateThumbnailFromImageAlways: true,
  330. kCGImageSourceShouldCacheImmediately: true,
  331. kCGImageSourceCreateThumbnailWithTransform: true,
  332. kCGImageSourceThumbnailMaxPixelSize: maxDimensionInPixels] as CFDictionary
  333. guard let downsampledImage = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, downsampleOptions) else {
  334. return nil
  335. }
  336. return KingfisherWrapper.image(cgImage: downsampledImage, scale: scale, refImage: nil)
  337. }
  338. }