Image.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  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(OSX)
  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(OSX)
  42. var CGImage: CGImageRef! {
  43. return CGImageForProposedRect(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 getAssociatedObject(self, associativeKey: &imagesKey)
  51. }
  52. set {
  53. setAssociatedObject(self, value: newValue, associativeKey: &imagesKey)
  54. }
  55. }
  56. private(set) var kf_duration: NSTimeInterval {
  57. get {
  58. return getAssociatedObject(self, associativeKey: &durationKey) ?? 0.0
  59. }
  60. set {
  61. setAssociatedObject(self, value: newValue, associativeKey: &durationKey)
  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: NSTimeInterval {
  72. return duration
  73. }
  74. private(set) var kf_imageSource: ImageSource? {
  75. get {
  76. return getAssociatedObject(self, associativeKey: &imageSourceKey)
  77. }
  78. set {
  79. setAssociatedObject(self, value: newValue, associativeKey: &imageSourceKey)
  80. }
  81. }
  82. private(set) var kf_animatedImageData: NSData? {
  83. get {
  84. return getAssociatedObject(self, associativeKey: &animatedImageDataKey)
  85. }
  86. set {
  87. setAssociatedObject(self, value: newValue, associativeKey: &animatedImageDataKey)
  88. }
  89. }
  90. #endif
  91. }
  92. // MARK: - Image Conversion
  93. extension Image {
  94. #if os(OSX)
  95. static func kf_imageWithCGImage(cgImage: CGImageRef, 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_normalizedImage() -> Image {
  103. return self
  104. }
  105. static func kf_animatedImageWithImages(images: [Image], duration: NSTimeInterval) -> Image? {
  106. return nil
  107. }
  108. #else
  109. static func kf_imageWithCGImage(cgImage: CGImageRef, 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_normalizedImage() -> 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. drawInRect(CGRect(origin: CGPoint.zero, size: size))
  130. let normalizedImage = UIGraphicsGetImageFromCurrentImageContext()
  131. UIGraphicsEndImageContext()
  132. return normalizedImage ?? self
  133. }
  134. static func kf_animatedImageWithImages(images: [Image], duration: NSTimeInterval) -> Image? {
  135. return Image.animatedImageWithImages(images, duration: duration)
  136. }
  137. #endif
  138. }
  139. // MARK: - PNG
  140. func ImagePNGRepresentation(image: Image) -> NSData? {
  141. #if os(OSX)
  142. if let cgimage = image.CGImage {
  143. let rep = NSBitmapImageRep(CGImage: cgimage)
  144. #if swift(>=2.3)
  145. return rep.representationUsingType(.PNG, properties:[:])
  146. #else
  147. return rep.representationUsingType(.NSPNGFileType, properties:[:])
  148. #endif
  149. }
  150. return nil
  151. #else
  152. return UIImagePNGRepresentation(image)
  153. #endif
  154. }
  155. // MARK: - JPEG
  156. func ImageJPEGRepresentation(image: Image, _ compressionQuality: CGFloat) -> NSData? {
  157. #if os(OSX)
  158. let rep = NSBitmapImageRep(CGImage: image.CGImage)
  159. #if swift(>=2.3)
  160. return rep.representationUsingType(.JPEG, properties: [NSImageCompressionFactor: compressionQuality])
  161. #else
  162. return rep.representationUsingType(.NSJPEGFileType, properties: [NSImageCompressionFactor: compressionQuality])
  163. #endif
  164. #else
  165. return UIImageJPEGRepresentation(image, compressionQuality)
  166. #endif
  167. }
  168. // MARK: - GIF
  169. func ImageGIFRepresentation(image: Image) -> NSData? {
  170. #if os(OSX)
  171. return ImageGIFRepresentation(image, duration: 0.0, repeatCount: 0)
  172. #else
  173. return image.kf_animatedImageData
  174. #endif
  175. }
  176. func ImageGIFRepresentation(image: Image, duration: NSTimeInterval, repeatCount: Int) -> NSData? {
  177. guard let images = image.kf_images else {
  178. return nil
  179. }
  180. let frameCount = images.count
  181. let gifDuration = duration <= 0.0 ? image.kf_duration / Double(frameCount) : duration / Double(frameCount)
  182. let frameProperties = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFDelayTime as String: gifDuration]]
  183. let imageProperties = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFLoopCount as String: repeatCount]]
  184. let data = NSMutableData()
  185. guard let destination = CGImageDestinationCreateWithData(data, kUTTypeGIF, frameCount, nil) else {
  186. return nil
  187. }
  188. CGImageDestinationSetProperties(destination, imageProperties)
  189. for image in images {
  190. CGImageDestinationAddImage(destination, image.CGImage!, frameProperties)
  191. }
  192. return CGImageDestinationFinalize(destination) ? NSData(data: data) : nil
  193. }
  194. func ImagesCountWithImageSource(ref: CGImageSourceRef) -> Int {
  195. return CGImageSourceGetCount(ref)
  196. }
  197. extension Image {
  198. static func kf_animatedImageWithGIFData(gifData data: NSData, preloadAll: Bool) -> Image? {
  199. return kf_animatedImageWithGIFData(gifData: data, scale: 1.0, duration: 0.0, preloadAll: preloadAll)
  200. }
  201. static func kf_animatedImageWithGIFData(gifData data: NSData, scale: CGFloat, duration: NSTimeInterval, preloadAll: Bool) -> Image? {
  202. func decodeFromSource(imageSource: CGImageSource, options: NSDictionary) -> ([Image], NSTimeInterval)? {
  203. //Calculates frame duration for a gif frame out of the kCGImagePropertyGIFDictionary dictionary
  204. func frameDuration(fromGifInfo gifInfo: NSDictionary) -> Double {
  205. let gifDefaultFrameDuration = 0.100
  206. let unclampedDelayTime = gifInfo[kCGImagePropertyGIFUnclampedDelayTime as String] as? NSNumber
  207. let delayTime = gifInfo[kCGImagePropertyGIFDelayTime as String] as? NSNumber
  208. let duration = unclampedDelayTime ?? delayTime
  209. guard let frameDuration = duration else { return gifDefaultFrameDuration }
  210. return frameDuration.doubleValue > 0.011 ? frameDuration.doubleValue : gifDefaultFrameDuration
  211. }
  212. let frameCount = CGImageSourceGetCount(imageSource)
  213. var images = [Image]()
  214. var gifDuration = 0.0
  215. for i in 0 ..< frameCount {
  216. guard let imageRef = CGImageSourceCreateImageAtIndex(imageSource, i, options) else {
  217. return nil
  218. }
  219. if frameCount == 1 {
  220. // Single frame
  221. gifDuration = Double.infinity
  222. } else {
  223. // Animated GIF
  224. guard let properties = CGImageSourceCopyPropertiesAtIndex(imageSource, i, nil),
  225. gifInfo = (properties as NSDictionary)[kCGImagePropertyGIFDictionary as String] as? NSDictionary else
  226. {
  227. return nil
  228. }
  229. gifDuration += frameDuration(fromGifInfo: gifInfo)
  230. }
  231. images.append(Image.kf_imageWithCGImage(imageRef, scale: scale, refImage: nil))
  232. }
  233. return (images, gifDuration)
  234. }
  235. // Start of kf_animatedImageWithGIFData
  236. let options: NSDictionary = [kCGImageSourceShouldCache as String: NSNumber(bool: true), kCGImageSourceTypeIdentifierHint as String: kUTTypeGIF]
  237. guard let imageSource = CGImageSourceCreateWithData(data, options) else {
  238. return nil
  239. }
  240. #if os(OSX)
  241. guard let (images, gifDuration) = decodeFromSource(imageSource, options: options) else {
  242. return nil
  243. }
  244. let image = Image(data: data)
  245. image?.kf_images = images
  246. image?.kf_duration = gifDuration
  247. return image
  248. #else
  249. if preloadAll {
  250. guard let (images, gifDuration) = decodeFromSource(imageSource, options: options) else {
  251. return nil
  252. }
  253. let image = Image.kf_animatedImageWithImages(images, duration: duration <= 0.0 ? gifDuration : duration)
  254. image?.kf_animatedImageData = data
  255. return image
  256. } else {
  257. let image = Image(data: data)
  258. image?.kf_animatedImageData = data
  259. image?.kf_imageSource = ImageSource(ref: imageSource)
  260. return image
  261. }
  262. #endif
  263. }
  264. }
  265. // MARK: - Create images from data
  266. extension Image {
  267. static func kf_imageWithData(data: NSData, scale: CGFloat, preloadAllGIFData: Bool) -> Image? {
  268. var image: Image?
  269. #if os(OSX)
  270. switch data.kf_imageFormat {
  271. case .JPEG: image = Image(data: data)
  272. case .PNG: image = Image(data: data)
  273. case .GIF: image = Image.kf_animatedImageWithGIFData(gifData: data, scale: scale, duration: 0.0, preloadAll: preloadAllGIFData)
  274. case .Unknown: image = Image(data: data)
  275. }
  276. #else
  277. switch data.kf_imageFormat {
  278. case .JPEG: image = Image(data: data, scale: scale)
  279. case .PNG: image = Image(data: data, scale: scale)
  280. case .GIF: image = Image.kf_animatedImageWithGIFData(gifData: data, scale: scale, duration: 0.0, preloadAll: preloadAllGIFData)
  281. case .Unknown: image = Image(data: data, scale: scale)
  282. }
  283. #endif
  284. return image
  285. }
  286. }
  287. // MARK: - Decode
  288. extension Image {
  289. func kf_decodedImage() -> Image? {
  290. return self.kf_decodedImage(scale: kf_scale)
  291. }
  292. func kf_decodedImage(scale scale: CGFloat) -> Image? {
  293. // prevent animated image (GIF) lose it's images
  294. #if os(iOS)
  295. if kf_imageSource != nil {
  296. return self
  297. }
  298. #else
  299. if kf_images != nil {
  300. return self
  301. }
  302. #endif
  303. let imageRef = self.CGImage
  304. let colorSpace = CGColorSpaceCreateDeviceRGB()
  305. let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedLast.rawValue).rawValue
  306. if let imageRef = imageRef, context = CGBitmapContextCreate(nil, CGImageGetWidth(imageRef), CGImageGetHeight(imageRef), 8, 0, colorSpace, bitmapInfo) {
  307. let rect = CGRect(x: 0, y: 0, width: CGImageGetWidth(imageRef), height: CGImageGetHeight(imageRef))
  308. CGContextDrawImage(context, rect, imageRef)
  309. let decompressedImageRef = CGBitmapContextCreateImage(context)
  310. return Image.kf_imageWithCGImage(decompressedImageRef!, scale: scale, refImage: self)
  311. } else {
  312. return nil
  313. }
  314. }
  315. }
  316. /// Reference the source image reference
  317. class ImageSource {
  318. var imageRef: CGImageSourceRef?
  319. init(ref: CGImageSourceRef) {
  320. self.imageRef = ref
  321. }
  322. }
  323. // MARK: - Image format
  324. private let pngHeader: [UInt8] = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]
  325. private let jpgHeaderSOI: [UInt8] = [0xFF, 0xD8]
  326. private let jpgHeaderIF: [UInt8] = [0xFF]
  327. private let gifHeader: [UInt8] = [0x47, 0x49, 0x46]
  328. enum ImageFormat {
  329. case Unknown, PNG, JPEG, GIF
  330. }
  331. extension NSData {
  332. var kf_imageFormat: ImageFormat {
  333. var buffer = [UInt8](count: 8, repeatedValue: 0)
  334. self.getBytes(&buffer, length: 8)
  335. if buffer == pngHeader {
  336. return .PNG
  337. } else if buffer[0] == jpgHeaderSOI[0] &&
  338. buffer[1] == jpgHeaderSOI[1] &&
  339. buffer[2] == jpgHeaderIF[0]
  340. {
  341. return .JPEG
  342. } else if buffer[0] == gifHeader[0] &&
  343. buffer[1] == gifHeader[1] &&
  344. buffer[2] == gifHeader[2]
  345. {
  346. return .GIF
  347. }
  348. return .Unknown
  349. }
  350. }