Image.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  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. #endif
  36. import ImageIO
  37. // MARK: - Image Properties
  38. extension Image {
  39. #if os(OSX)
  40. var CGImage: CGImageRef! {
  41. return CGImageForProposedRect(nil, context: nil, hints: nil)
  42. }
  43. var kf_scale: CGFloat {
  44. return 1.0
  45. }
  46. private(set) var kf_images: [Image]? {
  47. get {
  48. return objc_getAssociatedObject(self, &imagesKey) as? [Image]
  49. }
  50. set {
  51. objc_setAssociatedObject(self, &imagesKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
  52. }
  53. }
  54. private(set) var kf_duration: NSTimeInterval {
  55. get {
  56. return objc_getAssociatedObject(self, &durationKey) as? NSTimeInterval ?? 0.0
  57. }
  58. set {
  59. objc_setAssociatedObject(self, &durationKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
  60. }
  61. }
  62. #else
  63. var kf_scale: CGFloat {
  64. return scale
  65. }
  66. var kf_images: [Image]? {
  67. return images
  68. }
  69. var kf_duration: NSTimeInterval {
  70. return duration
  71. }
  72. #endif
  73. }
  74. // MARK: - Image Conversion
  75. extension Image {
  76. #if os(OSX)
  77. static func kf_imageWithCGImage(cgImage: CGImageRef, scale: CGFloat, refImage: Image?) -> Image {
  78. return Image(CGImage: cgImage, size: CGSize.zero)
  79. }
  80. /**
  81. Normalize the image. This method does nothing in OS X.
  82. - returns: The image itself.
  83. */
  84. public func kf_normalizedImage() -> Image {
  85. return self
  86. }
  87. static func kf_animatedImageWithImages(images: [Image], duration: NSTimeInterval) -> Image? {
  88. return nil
  89. }
  90. #else
  91. static func kf_imageWithCGImage(cgImage: CGImageRef, scale: CGFloat, refImage: Image?) -> Image {
  92. if let refImage = refImage {
  93. return Image(CGImage: cgImage, scale: scale, orientation: refImage.imageOrientation)
  94. } else {
  95. return Image(CGImage: cgImage, scale: scale, orientation: .Up)
  96. }
  97. }
  98. /**
  99. Normalize the image. This method will try to redraw an image with orientation and scale considered.
  100. - returns: The normalized image with orientation set to up and correct scale.
  101. */
  102. public func kf_normalizedImage() -> Image {
  103. // prevent animated image (GIF) lose it's images
  104. if images != nil {
  105. return self
  106. }
  107. if imageOrientation == .Up {
  108. return self
  109. }
  110. UIGraphicsBeginImageContextWithOptions(size, false, scale)
  111. drawInRect(CGRect(origin: CGPoint.zero, size: size))
  112. let normalizedImage = UIGraphicsGetImageFromCurrentImageContext()
  113. UIGraphicsEndImageContext()
  114. return normalizedImage
  115. }
  116. static func kf_animatedImageWithImages(images: [Image], duration: NSTimeInterval) -> Image? {
  117. return Image.animatedImageWithImages(images, duration: duration)
  118. }
  119. #endif
  120. }
  121. // MARK: - PNG
  122. func ImagePNGRepresentation(image: Image) -> NSData? {
  123. #if os(OSX)
  124. if let cgimage = image.CGImage {
  125. let rep = NSBitmapImageRep(CGImage: cgimage)
  126. return rep.representationUsingType(.NSPNGFileType, properties:[:])
  127. }
  128. return nil
  129. #else
  130. return UIImagePNGRepresentation(image)
  131. #endif
  132. }
  133. // MARK: - JPEG
  134. func ImageJPEGRepresentation(image: Image, _ compressionQuality: CGFloat) -> NSData? {
  135. #if os(OSX)
  136. let rep = NSBitmapImageRep(CGImage: image.CGImage)
  137. return rep.representationUsingType(.NSJPEGFileType, properties: [NSImageCompressionFactor: compressionQuality])
  138. #else
  139. return UIImageJPEGRepresentation(image, compressionQuality)
  140. #endif
  141. }
  142. // MARK: - GIF
  143. func ImageGIFRepresentation(image: Image) -> NSData? {
  144. return ImageGIFRepresentation(image, duration: 0.0, repeatCount: 0)
  145. }
  146. func ImageGIFRepresentation(image: Image, duration: NSTimeInterval, repeatCount: Int) -> NSData? {
  147. guard let images = image.kf_images else {
  148. return nil
  149. }
  150. let frameCount = images.count
  151. let gifDuration = duration <= 0.0 ? image.kf_duration / Double(frameCount) : duration / Double(frameCount)
  152. let frameProperties = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFDelayTime as String: gifDuration]]
  153. let imageProperties = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFLoopCount as String: repeatCount]]
  154. let data = NSMutableData()
  155. guard let destination = CGImageDestinationCreateWithData(data, kUTTypeGIF, frameCount, nil) else {
  156. return nil
  157. }
  158. CGImageDestinationSetProperties(destination, imageProperties)
  159. for image in images {
  160. CGImageDestinationAddImage(destination, image.CGImage!, frameProperties)
  161. }
  162. return CGImageDestinationFinalize(destination) ? NSData(data: data) : nil
  163. }
  164. extension Image {
  165. static func kf_animatedImageWithGIFData(gifData data: NSData) -> Image? {
  166. return kf_animatedImageWithGIFData(gifData: data, scale: 1.0, duration: 0.0)
  167. }
  168. static func kf_animatedImageWithGIFData(gifData data: NSData, scale: CGFloat, duration: NSTimeInterval) -> Image? {
  169. let options: NSDictionary = [kCGImageSourceShouldCache as String: NSNumber(bool: true), kCGImageSourceTypeIdentifierHint as String: kUTTypeGIF]
  170. guard let imageSource = CGImageSourceCreateWithData(data, options) else {
  171. return nil
  172. }
  173. let frameCount = CGImageSourceGetCount(imageSource)
  174. var images = [Image]()
  175. var gifDuration = 0.0
  176. for i in 0 ..< frameCount {
  177. guard let imageRef = CGImageSourceCreateImageAtIndex(imageSource, i, options) else {
  178. return nil
  179. }
  180. if frameCount == 1 {
  181. // Single frame
  182. gifDuration = Double.infinity
  183. } else {
  184. // Animated GIF
  185. guard let properties = CGImageSourceCopyPropertiesAtIndex(imageSource, i, nil),
  186. gifInfo = (properties as NSDictionary)[kCGImagePropertyGIFDictionary as String] as? NSDictionary,
  187. frameDuration = (gifInfo[kCGImagePropertyGIFDelayTime as String] as? NSNumber) else
  188. {
  189. return nil
  190. }
  191. gifDuration += frameDuration.doubleValue
  192. }
  193. images.append(Image.kf_imageWithCGImage(imageRef, scale: scale, refImage: nil))
  194. }
  195. #if os(OSX)
  196. if let image = Image(data: data) {
  197. image.kf_images = images
  198. image.kf_duration = gifDuration
  199. return image
  200. }
  201. return nil
  202. #else
  203. return Image.kf_animatedImageWithImages(images, duration: duration <= 0.0 ? gifDuration : duration)
  204. #endif
  205. }
  206. }
  207. // MARK: - Create images from data
  208. extension Image {
  209. static func kf_imageWithData(data: NSData, scale: CGFloat) -> Image? {
  210. var image: Image?
  211. #if os(OSX)
  212. switch data.kf_imageFormat {
  213. case .JPEG: image = Image(data: data)
  214. case .PNG: image = Image(data: data)
  215. case .GIF: image = Image.kf_animatedImageWithGIFData(gifData: data, scale: scale, duration: 0.0)
  216. case .Unknown: image = Image(data: data)
  217. }
  218. #else
  219. switch data.kf_imageFormat {
  220. case .JPEG: image = Image(data: data, scale: scale)
  221. case .PNG: image = Image(data: data, scale: scale)
  222. case .GIF: image = Image.kf_animatedImageWithGIFData(gifData: data, scale: scale, duration: 0.0)
  223. case .Unknown: image = Image(data: data, scale: scale)
  224. }
  225. #endif
  226. return image
  227. }
  228. }
  229. // MARK: - Decode
  230. extension Image {
  231. func kf_decodedImage() -> Image? {
  232. return self.kf_decodedImage(scale: kf_scale)
  233. }
  234. func kf_decodedImage(scale scale: CGFloat) -> Image? {
  235. // prevent animated image (GIF) lose it's images
  236. if kf_images != nil {
  237. return self
  238. }
  239. let imageRef = self.CGImage
  240. let colorSpace = CGColorSpaceCreateDeviceRGB()
  241. let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedLast.rawValue).rawValue
  242. let context = CGBitmapContextCreate(nil, CGImageGetWidth(imageRef), CGImageGetHeight(imageRef), 8, 0, colorSpace, bitmapInfo)
  243. if let context = context {
  244. let rect = CGRect(x: 0, y: 0, width: CGImageGetWidth(imageRef), height: CGImageGetHeight(imageRef))
  245. CGContextDrawImage(context, rect, imageRef)
  246. let decompressedImageRef = CGBitmapContextCreateImage(context)
  247. return Image.kf_imageWithCGImage(decompressedImageRef!, scale: scale, refImage: self)
  248. } else {
  249. return nil
  250. }
  251. }
  252. }
  253. // MARK: - Image format
  254. private let pngHeader: [UInt8] = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]
  255. private let jpgHeaderSOI: [UInt8] = [0xFF, 0xD8]
  256. private let jpgHeaderIF: [UInt8] = [0xFF]
  257. private let gifHeader: [UInt8] = [0x47, 0x49, 0x46]
  258. enum ImageFormat {
  259. case Unknown, PNG, JPEG, GIF
  260. }
  261. extension NSData {
  262. var kf_imageFormat: ImageFormat {
  263. var buffer = [UInt8](count: 8, repeatedValue: 0)
  264. self.getBytes(&buffer, length: 8)
  265. if buffer == pngHeader {
  266. return .PNG
  267. } else if buffer[0] == jpgHeaderSOI[0] &&
  268. buffer[1] == jpgHeaderSOI[1] &&
  269. buffer[2] == jpgHeaderIF[0]
  270. {
  271. return .JPEG
  272. } else if buffer[0] == gifHeader[0] &&
  273. buffer[1] == gifHeader[1] &&
  274. buffer[2] == gifHeader[2]
  275. {
  276. return .GIF
  277. }
  278. return .Unknown
  279. }
  280. }