Image.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. //
  2. // Image.swift
  3. // Kingfisher
  4. //
  5. // Created by Wei Wang on 16/1/6.
  6. //
  7. // Copyright (c) 2016 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.NSImage
  28. public typealias Image = NSImage
  29. private var imagesKey: Void?
  30. private var durationKey: Void?
  31. #else
  32. import UIKit.UIImage
  33. import MobileCoreServices
  34. public typealias Image = UIImage
  35. private var imageSourceKey: Void?
  36. private var animatedImageDataKey: Void?
  37. #endif
  38. import ImageIO
  39. // MARK: - Image Properties
  40. extension Image {
  41. #if os(macOS)
  42. var cgImage: CGImage! {
  43. return cgImage(forProposedRect: nil, context: nil, hints: nil)
  44. }
  45. var kf_scale: CGFloat {
  46. return 1.0
  47. }
  48. private(set) var kf_images: [Image]? {
  49. get {
  50. return objc_getAssociatedObject(self, &imagesKey) as? [Image]
  51. }
  52. set {
  53. objc_setAssociatedObject(self, &imagesKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
  54. }
  55. }
  56. private(set) var kf_duration: TimeInterval {
  57. get {
  58. return objc_getAssociatedObject(self, &durationKey) as? TimeInterval ?? 0.0
  59. }
  60. set {
  61. objc_setAssociatedObject(self, &durationKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
  62. }
  63. }
  64. #else
  65. var kf_scale: CGFloat {
  66. return scale
  67. }
  68. var kf_images: [Image]? {
  69. return images
  70. }
  71. var kf_duration: TimeInterval {
  72. return duration
  73. }
  74. private(set) var kf_imageSource: ImageSource? {
  75. get {
  76. return objc_getAssociatedObject(self, &imageSourceKey) as? ImageSource
  77. }
  78. set {
  79. objc_setAssociatedObject(self, &imageSourceKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
  80. }
  81. }
  82. private(set) var kf_animatedImageData: Data? {
  83. get {
  84. return objc_getAssociatedObject(self, &animatedImageDataKey) as? Data
  85. }
  86. set {
  87. objc_setAssociatedObject(self, &animatedImageDataKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
  88. }
  89. }
  90. #endif
  91. }
  92. // MARK: - Image Conversion
  93. extension Image {
  94. #if os(macOS)
  95. static func kf_image(cgImage: CGImage, scale: CGFloat, refImage: Image?) -> Image {
  96. return Image(cgImage: cgImage, size: CGSize.zero)
  97. }
  98. /**
  99. Normalize the image. This method does nothing in OS X.
  100. - returns: The image itself.
  101. */
  102. public func kf_normalized() -> Image {
  103. return self
  104. }
  105. static func kf_animatedImage(images: [Image], duration: TimeInterval) -> Image? {
  106. return nil
  107. }
  108. #else
  109. static func kf_image(cgImage: CGImage, scale: CGFloat, refImage: Image?) -> Image {
  110. if let refImage = refImage {
  111. return Image(cgImage: cgImage, scale: scale, orientation: refImage.imageOrientation)
  112. } else {
  113. return Image(cgImage: cgImage, scale: scale, orientation: .up)
  114. }
  115. }
  116. /**
  117. Normalize the image. This method will try to redraw an image with orientation and scale considered.
  118. - returns: The normalized image with orientation set to up and correct scale.
  119. */
  120. public func kf_normalized() -> Image {
  121. // prevent animated image (GIF) lose it's images
  122. if images != nil {
  123. return self
  124. }
  125. if imageOrientation == .up {
  126. return self
  127. }
  128. UIGraphicsBeginImageContextWithOptions(size, false, scale)
  129. draw(in: CGRect(origin: CGPoint.zero, size: size))
  130. let normalizedImage = UIGraphicsGetImageFromCurrentImageContext()
  131. UIGraphicsEndImageContext()
  132. return normalizedImage!
  133. }
  134. static func kf_animated(with images: [Image], forDuration duration: TimeInterval) -> Image? {
  135. return Image.animatedImage(with: images, duration: duration)
  136. }
  137. #endif
  138. }
  139. extension Image {
  140. // MARK: - PNG
  141. func pngRepresentation() -> Data? {
  142. #if os(macOS)
  143. if let cgimage = cgImage {
  144. let rep = NSBitmapImageRep(cgImage: cgimage)
  145. return rep.representation(using: .PNG, properties: [:])
  146. }
  147. return nil
  148. #else
  149. return UIImagePNGRepresentation(self)
  150. #endif
  151. }
  152. // MARK: - JPEG
  153. func jpegRepresentation(compressionQuality: CGFloat) -> Data? {
  154. #if os(macOS)
  155. let rep = NSBitmapImageRep(cgImage: cgImage)
  156. return rep.representation(using:.JPEG, properties: [NSImageCompressionFactor: compressionQuality])
  157. #else
  158. return UIImageJPEGRepresentation(self, compressionQuality)
  159. #endif
  160. }
  161. func gifRepresentation() -> Data? {
  162. #if os(macOS)
  163. return gifRepresentation(duration: 0.0, repeatCount: 0)
  164. #else
  165. return kf_animatedImageData
  166. #endif
  167. }
  168. func gifRepresentation(duration: TimeInterval, repeatCount: Int) -> Data? {
  169. guard let images = kf_images else {
  170. return nil
  171. }
  172. let frameCount = images.count
  173. let gifDuration = duration <= 0.0 ? kf_duration / Double(frameCount) : duration / Double(frameCount)
  174. let frameProperties = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFDelayTime as String: gifDuration]]
  175. let imageProperties = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFLoopCount as String: repeatCount]]
  176. let data = NSMutableData()
  177. guard let destination = CGImageDestinationCreateWithData(data, kUTTypeGIF, frameCount, nil) else {
  178. return nil
  179. }
  180. CGImageDestinationSetProperties(destination, imageProperties)
  181. for image in images {
  182. CGImageDestinationAddImage(destination, image.cgImage!, frameProperties)
  183. }
  184. return CGImageDestinationFinalize(destination) ? data.copy() as? Data : nil
  185. }
  186. }
  187. extension Image {
  188. static func kf_animated(with data: Data, preloadAll: Bool) -> Image? {
  189. return kf_animated(with: data, scale: 1.0, duration: 0.0, preloadAll: preloadAll)
  190. }
  191. static func kf_animated(with data: Data, scale: CGFloat, duration: TimeInterval, preloadAll: Bool) -> Image? {
  192. func decode(from imageSource: CGImageSource, for options: NSDictionary) -> ([Image], TimeInterval)? {
  193. //Calculates frame duration for a gif frame out of the kCGImagePropertyGIFDictionary dictionary
  194. func frameDuration(from gifInfo: NSDictionary) -> Double {
  195. let gifDefaultFrameDuration = 0.100
  196. let unclampedDelayTime = gifInfo[kCGImagePropertyGIFUnclampedDelayTime as String] as? NSNumber
  197. let delayTime = gifInfo[kCGImagePropertyGIFDelayTime as String] as? NSNumber
  198. let duration = unclampedDelayTime ?? delayTime
  199. guard let frameDuration = duration else { return gifDefaultFrameDuration }
  200. return frameDuration.doubleValue > 0.011 ? frameDuration.doubleValue : gifDefaultFrameDuration
  201. }
  202. let frameCount = CGImageSourceGetCount(imageSource)
  203. var images = [Image]()
  204. var gifDuration = 0.0
  205. for i in 0 ..< frameCount {
  206. guard let imageRef = CGImageSourceCreateImageAtIndex(imageSource, i, options) else {
  207. return nil
  208. }
  209. if frameCount == 1 {
  210. // Single frame
  211. gifDuration = Double.infinity
  212. } else {
  213. // Animated GIF
  214. guard let properties = CGImageSourceCopyPropertiesAtIndex(imageSource, i, nil),
  215. let gifInfo = (properties as NSDictionary)[kCGImagePropertyGIFDictionary as String] as? NSDictionary else
  216. {
  217. return nil
  218. }
  219. gifDuration += frameDuration(from: gifInfo)
  220. }
  221. images.append(Image.kf_image(cgImage: imageRef, scale: scale, refImage: nil))
  222. }
  223. return (images, gifDuration)
  224. }
  225. // Start of kf_animatedImageWithGIFData
  226. let options: NSDictionary = [kCGImageSourceShouldCache as String: true, kCGImageSourceTypeIdentifierHint as String: kUTTypeGIF]
  227. guard let imageSource = CGImageSourceCreateWithData(data, options) else {
  228. return nil
  229. }
  230. #if os(macOS)
  231. guard let (images, gifDuration) = decode(from: imageSource, for: options) else {
  232. return nil
  233. }
  234. let image = Image(data: data)
  235. image?.kf_images = images
  236. image?.kf_duration = gifDuration
  237. return image
  238. #else
  239. if preloadAll {
  240. guard let (images, gifDuration) = decode(from: imageSource, for: options) else {
  241. return nil
  242. }
  243. let image = Image.kf_animated(with: images, forDuration: duration <= 0.0 ? gifDuration : duration)
  244. image?.kf_animatedImageData = data
  245. return image
  246. } else {
  247. let image = Image(data: data)
  248. image?.kf_animatedImageData = data
  249. image?.kf_imageSource = ImageSource(ref: imageSource)
  250. return image
  251. }
  252. #endif
  253. }
  254. }
  255. // MARK: - Create images from data
  256. extension Image {
  257. static func kf_image(data: Data, scale: CGFloat, preloadAllGIFData: Bool) -> Image? {
  258. var image: Image?
  259. #if os(macOS)
  260. switch data.kf_imageFormat {
  261. case .JPEG: image = Image(data: data)
  262. case .PNG: image = Image(data: data)
  263. case .GIF: image = Image.kf_animated(with: data, scale: scale, duration: 0.0, preloadAll: preloadAllGIFData)
  264. case .unknown: image = Image(data: data)
  265. }
  266. #else
  267. switch data.kf_imageFormat {
  268. case .JPEG: image = Image(data: data, scale: scale)
  269. case .PNG: image = Image(data: data, scale: scale)
  270. case .GIF: image = Image.kf_animated(with: data, scale: scale, duration: 0.0, preloadAll: preloadAllGIFData)
  271. case .unknown: image = Image(data: data, scale: scale)
  272. }
  273. #endif
  274. return image
  275. }
  276. }
  277. // MARK: - Decode
  278. extension Image {
  279. func kf_decoded() -> Image? {
  280. return self.kf_decoded(scale: kf_scale)
  281. }
  282. func kf_decoded(scale: CGFloat) -> Image? {
  283. // prevent animated image (GIF) lose it's images
  284. #if os(iOS)
  285. if kf_imageSource != nil {
  286. return self
  287. }
  288. #else
  289. if kf_images != nil {
  290. return self
  291. }
  292. #endif
  293. let imageRef = self.cgImage
  294. let colorSpace = CGColorSpaceCreateDeviceRGB()
  295. let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue).rawValue
  296. let context = CGContext(data: nil, width: (imageRef?.width)!, height: (imageRef?.height)!, bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: bitmapInfo)
  297. if let context = context {
  298. let rect = CGRect(x: 0, y: 0, width: (imageRef?.width)!, height: (imageRef?.height)!)
  299. context.draw(in: rect, image: imageRef!)
  300. let decompressedImageRef = context.makeImage()
  301. return Image.kf_image(cgImage: decompressedImageRef!, scale: scale, refImage: self)
  302. } else {
  303. return nil
  304. }
  305. }
  306. }
  307. /// Reference the source image reference
  308. class ImageSource {
  309. var imageRef: CGImageSource?
  310. init(ref: CGImageSource) {
  311. self.imageRef = ref
  312. }
  313. }
  314. // MARK: - Image format
  315. private struct ImageHeaderData {
  316. static var PNG: [UInt8] = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]
  317. static var JPEG_SOI: [UInt8] = [0xFF, 0xD8]
  318. static var JPEG_IF: [UInt8] = [0xFF]
  319. static var GIF: [UInt8] = [0x47, 0x49, 0x46]
  320. }
  321. enum ImageFormat {
  322. case unknown, PNG, JPEG, GIF
  323. }
  324. extension Data {
  325. var kf_imageFormat: ImageFormat {
  326. var buffer = [UInt8](repeating: 0, count: 8)
  327. (self as NSData).getBytes(&buffer, length: 8)
  328. if buffer == ImageHeaderData.PNG {
  329. return .PNG
  330. } else if buffer[0] == ImageHeaderData.JPEG_SOI[0] &&
  331. buffer[1] == ImageHeaderData.JPEG_SOI[1] &&
  332. buffer[2] == ImageHeaderData.JPEG_IF[0]
  333. {
  334. return .JPEG
  335. } else if buffer[0] == ImageHeaderData.GIF[0] &&
  336. buffer[1] == ImageHeaderData.GIF[1] &&
  337. buffer[2] == ImageHeaderData.GIF[2]
  338. {
  339. return .GIF
  340. }
  341. return .unknown
  342. }
  343. }