Image.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  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 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: NSTimeInterval {
  57. get {
  58. return objc_getAssociatedObject(self, &durationKey) as? NSTimeInterval ?? 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: NSTimeInterval {
  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: NSData? {
  83. get {
  84. return objc_getAssociatedObject(self, &animatedImageDataKey) as? NSData
  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(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
  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. return rep.representationUsingType(.NSPNGFileType, properties:[:])
  145. }
  146. return nil
  147. #else
  148. return UIImagePNGRepresentation(image)
  149. #endif
  150. }
  151. // MARK: - JPEG
  152. func ImageJPEGRepresentation(image: Image, _ compressionQuality: CGFloat) -> NSData? {
  153. #if os(OSX)
  154. let rep = NSBitmapImageRep(CGImage: image.CGImage)
  155. return rep.representationUsingType(.NSJPEGFileType, properties: [NSImageCompressionFactor: compressionQuality])
  156. #else
  157. return UIImageJPEGRepresentation(image, compressionQuality)
  158. #endif
  159. }
  160. // MARK: - GIF
  161. func ImageGIFRepresentation(image: Image) -> NSData? {
  162. #if os(OSX)
  163. return ImageGIFRepresentation(image, duration: 0.0, repeatCount: 0)
  164. #else
  165. return image.kf_animatedImageData
  166. #endif
  167. }
  168. func ImageGIFRepresentation(image: Image, duration: NSTimeInterval, repeatCount: Int) -> NSData? {
  169. guard let images = image.kf_images else {
  170. return nil
  171. }
  172. let frameCount = images.count
  173. let gifDuration = duration <= 0.0 ? image.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) ? NSData(data: data) : nil
  185. }
  186. func ImagesCountWithImageSource(ref: CGImageSourceRef) -> Int {
  187. return CGImageSourceGetCount(ref)
  188. }
  189. extension Image {
  190. static func kf_animatedImageWithGIFData(gifData data: NSData, preloadAll: Bool) -> Image? {
  191. return kf_animatedImageWithGIFData(gifData: data, scale: 1.0, duration: 0.0, preloadAll: preloadAll)
  192. }
  193. static func kf_animatedImageWithGIFData(gifData data: NSData, scale: CGFloat, duration: NSTimeInterval, preloadAll: Bool) -> Image? {
  194. func decodeFromSource(imageSource: CGImageSource, options: NSDictionary) -> ([Image], NSTimeInterval)? {
  195. let frameCount = CGImageSourceGetCount(imageSource)
  196. var images = [Image]()
  197. var gifDuration = 0.0
  198. for i in 0 ..< frameCount {
  199. guard let imageRef = CGImageSourceCreateImageAtIndex(imageSource, i, options) else {
  200. return nil
  201. }
  202. if frameCount == 1 {
  203. // Single frame
  204. gifDuration = Double.infinity
  205. } else {
  206. // Animated GIF
  207. guard let properties = CGImageSourceCopyPropertiesAtIndex(imageSource, i, nil),
  208. gifInfo = (properties as NSDictionary)[kCGImagePropertyGIFDictionary as String] as? NSDictionary,
  209. frameDuration = (gifInfo[kCGImagePropertyGIFDelayTime as String] as? NSNumber) else
  210. {
  211. return nil
  212. }
  213. gifDuration += frameDuration.doubleValue
  214. }
  215. images.append(Image.kf_imageWithCGImage(imageRef, scale: scale, refImage: nil))
  216. }
  217. return (images, gifDuration)
  218. }
  219. // Start of kf_animatedImageWithGIFData
  220. let options: NSDictionary = [kCGImageSourceShouldCache as String: NSNumber(bool: true), kCGImageSourceTypeIdentifierHint as String: kUTTypeGIF]
  221. guard let imageSource = CGImageSourceCreateWithData(data, options) else {
  222. return nil
  223. }
  224. #if os(OSX)
  225. guard let (images, gifDuration) = decodeFromSource(imageSource, options: options) else {
  226. return nil
  227. }
  228. let image = Image(data: data)
  229. image?.kf_images = images
  230. image?.kf_duration = gifDuration
  231. return image
  232. #else
  233. if preloadAll {
  234. guard let (images, gifDuration) = decodeFromSource(imageSource, options: options) else {
  235. return nil
  236. }
  237. let image = Image.kf_animatedImageWithImages(images, duration: duration <= 0.0 ? gifDuration : duration)
  238. image?.kf_animatedImageData = data
  239. return image
  240. } else {
  241. let image = Image(data: data)
  242. image?.kf_animatedImageData = data
  243. image?.kf_imageSource = ImageSource(ref: imageSource)
  244. return image
  245. }
  246. #endif
  247. }
  248. }
  249. // MARK: - Create images from data
  250. extension Image {
  251. static func kf_imageWithData(data: NSData, scale: CGFloat, preloadAllGIFData: Bool) -> Image? {
  252. var image: Image?
  253. #if os(OSX)
  254. switch data.kf_imageFormat {
  255. case .JPEG: image = Image(data: data)
  256. case .PNG: image = Image(data: data)
  257. case .GIF: image = Image.kf_animatedImageWithGIFData(gifData: data, scale: scale, duration: 0.0, preloadAll: preloadAllGIFData)
  258. case .Unknown: image = Image(data: data)
  259. }
  260. #else
  261. switch data.kf_imageFormat {
  262. case .JPEG: image = Image(data: data, scale: scale)
  263. case .PNG: image = Image(data: data, scale: scale)
  264. case .GIF: image = Image.kf_animatedImageWithGIFData(gifData: data, scale: scale, duration: 0.0, preloadAll: preloadAllGIFData)
  265. case .Unknown: image = Image(data: data, scale: scale)
  266. }
  267. #endif
  268. return image
  269. }
  270. }
  271. // MARK: - Decode
  272. extension Image {
  273. func kf_decodedImage() -> Image? {
  274. return self.kf_decodedImage(scale: kf_scale)
  275. }
  276. func kf_decodedImage(scale scale: CGFloat) -> Image? {
  277. // prevent animated image (GIF) lose it's images
  278. #if os(iOS)
  279. if kf_imageSource != nil {
  280. return self
  281. }
  282. #else
  283. if kf_images != nil {
  284. return self
  285. }
  286. #endif
  287. let imageRef = self.CGImage
  288. let colorSpace = CGColorSpaceCreateDeviceRGB()
  289. let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedLast.rawValue).rawValue
  290. let context = CGBitmapContextCreate(nil, CGImageGetWidth(imageRef), CGImageGetHeight(imageRef), 8, 0, colorSpace, bitmapInfo)
  291. if let context = context {
  292. let rect = CGRect(x: 0, y: 0, width: CGImageGetWidth(imageRef), height: CGImageGetHeight(imageRef))
  293. CGContextDrawImage(context, rect, imageRef)
  294. let decompressedImageRef = CGBitmapContextCreateImage(context)
  295. return Image.kf_imageWithCGImage(decompressedImageRef!, scale: scale, refImage: self)
  296. } else {
  297. return nil
  298. }
  299. }
  300. }
  301. /// Reference the source image reference
  302. class ImageSource {
  303. var imageRef: CGImageSourceRef?
  304. init(ref: CGImageSourceRef) {
  305. self.imageRef = ref
  306. }
  307. }
  308. // MARK: - Image format
  309. private let pngHeader: [UInt8] = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]
  310. private let jpgHeaderSOI: [UInt8] = [0xFF, 0xD8]
  311. private let jpgHeaderIF: [UInt8] = [0xFF]
  312. private let gifHeader: [UInt8] = [0x47, 0x49, 0x46]
  313. enum ImageFormat {
  314. case Unknown, PNG, JPEG, GIF
  315. }
  316. extension NSData {
  317. var kf_imageFormat: ImageFormat {
  318. var buffer = [UInt8](count: 8, repeatedValue: 0)
  319. self.getBytes(&buffer, length: 8)
  320. if buffer == pngHeader {
  321. return .PNG
  322. } else if buffer[0] == jpgHeaderSOI[0] &&
  323. buffer[1] == jpgHeaderSOI[1] &&
  324. buffer[2] == jpgHeaderIF[0]
  325. {
  326. return .JPEG
  327. } else if buffer[0] == gifHeader[0] &&
  328. buffer[1] == gifHeader[1] &&
  329. buffer[2] == gifHeader[2]
  330. {
  331. return .GIF
  332. }
  333. return .Unknown
  334. }
  335. }