Image.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  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: CGSizeZero)
  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 sclae 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: CGPointZero, 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. let rep = NSBitmapImageRep(CGImage: image.CGImage)
  125. return rep.representationUsingType(.NSPNGFileType, properties:[:])
  126. #else
  127. return UIImagePNGRepresentation(image)
  128. #endif
  129. }
  130. // MARK: - JPEG
  131. func ImageJPEGRepresentation(image: Image, _ compressionQuality: CGFloat) -> NSData? {
  132. #if os(OSX)
  133. let rep = NSBitmapImageRep(CGImage: image.CGImage)
  134. return rep.representationUsingType(.NSJPEGFileType, properties: [NSImageCompressionFactor: compressionQuality])
  135. #else
  136. return UIImageJPEGRepresentation(image, compressionQuality)
  137. #endif
  138. }
  139. // MARK: - GIF
  140. func ImageGIFRepresentation(image: Image) -> NSData? {
  141. return ImageGIFRepresentation(image, duration: 0.0, repeatCount: 0)
  142. }
  143. func ImageGIFRepresentation(image: Image, duration: NSTimeInterval, repeatCount: Int) -> NSData? {
  144. guard let images = image.kf_images else {
  145. return nil
  146. }
  147. let frameCount = images.count
  148. let gifDuration = duration <= 0.0 ? image.kf_duration / Double(frameCount) : duration / Double(frameCount)
  149. let frameProperties = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFDelayTime as String: gifDuration]]
  150. let imageProperties = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFLoopCount as String: repeatCount]]
  151. let data = NSMutableData()
  152. guard let destination = CGImageDestinationCreateWithData(data, kUTTypeGIF, frameCount, nil) else {
  153. return nil
  154. }
  155. CGImageDestinationSetProperties(destination, imageProperties)
  156. for image in images {
  157. CGImageDestinationAddImage(destination, image.CGImage!, frameProperties)
  158. }
  159. return CGImageDestinationFinalize(destination) ? NSData(data: data) : nil
  160. }
  161. extension Image {
  162. static func kf_animatedImageWithGIFData(gifData data: NSData) -> Image? {
  163. return kf_animatedImageWithGIFData(gifData: data, scale: 1.0, duration: 0.0)
  164. }
  165. static func kf_animatedImageWithGIFData(gifData data: NSData, scale: CGFloat, duration: NSTimeInterval) -> Image? {
  166. let options: NSDictionary = [kCGImageSourceShouldCache as String: NSNumber(bool: true), kCGImageSourceTypeIdentifierHint as String: kUTTypeGIF]
  167. guard let imageSource = CGImageSourceCreateWithData(data, options) else {
  168. return nil
  169. }
  170. let frameCount = CGImageSourceGetCount(imageSource)
  171. var images = [Image]()
  172. var gifDuration = 0.0
  173. for i in 0 ..< frameCount {
  174. guard let imageRef = CGImageSourceCreateImageAtIndex(imageSource, i, options) else {
  175. return nil
  176. }
  177. guard let properties = CGImageSourceCopyPropertiesAtIndex(imageSource, i, nil),
  178. gifInfo = (properties as NSDictionary)[kCGImagePropertyGIFDictionary as String] as? NSDictionary,
  179. frameDuration = (gifInfo[kCGImagePropertyGIFDelayTime as String] as? NSNumber) else
  180. {
  181. return nil
  182. }
  183. gifDuration += frameDuration.doubleValue
  184. images.append(Image.kf_imageWithCGImage(imageRef, scale: scale, refImage: nil))
  185. }
  186. #if os(OSX)
  187. if let image = Image(data: data) {
  188. image.kf_images = images
  189. image.kf_duration = gifDuration
  190. return image
  191. }
  192. return nil
  193. #else
  194. if frameCount == 1 {
  195. return images.first
  196. } else {
  197. return Image.kf_animatedImageWithImages(images, duration: duration <= 0.0 ? gifDuration : duration)
  198. }
  199. #endif
  200. }
  201. }
  202. // MARK: - Create images from data
  203. extension Image {
  204. static func kf_imageWithData(data: NSData, scale: CGFloat) -> Image? {
  205. var image: Image?
  206. #if os(OSX)
  207. switch data.kf_imageFormat {
  208. case .JPEG: image = Image(data: data)
  209. case .PNG: image = Image(data: data)
  210. case .GIF: image = Image.kf_animatedImageWithGIFData(gifData: data, scale: scale, duration: 0.0)
  211. case .Unknown: image = nil
  212. }
  213. #else
  214. switch data.kf_imageFormat {
  215. case .JPEG: image = Image(data: data, scale: scale)
  216. case .PNG: image = Image(data: data, scale: scale)
  217. case .GIF: image = Image.kf_animatedImageWithGIFData(gifData: data, scale: scale, duration: 0.0)
  218. case .Unknown: image = nil
  219. }
  220. #endif
  221. return image
  222. }
  223. }
  224. // MARK: - Decode
  225. extension Image {
  226. func kf_decodedImage() -> Image? {
  227. return self.kf_decodedImage(scale: kf_scale)
  228. }
  229. func kf_decodedImage(scale scale: CGFloat) -> Image? {
  230. // prevent animated image (GIF) lose it's images
  231. if kf_images != nil {
  232. return self
  233. }
  234. let imageRef = self.CGImage
  235. let colorSpace = CGColorSpaceCreateDeviceRGB()
  236. let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedLast.rawValue).rawValue
  237. let contextHolder = UnsafeMutablePointer<Void>()
  238. let context = CGBitmapContextCreate(contextHolder, CGImageGetWidth(imageRef), CGImageGetHeight(imageRef), 8, 0, colorSpace, bitmapInfo)
  239. if let context = context {
  240. let rect = CGRect(x: 0, y: 0, width: CGImageGetWidth(imageRef), height: CGImageGetHeight(imageRef))
  241. CGContextDrawImage(context, rect, imageRef)
  242. let decompressedImageRef = CGBitmapContextCreateImage(context)
  243. return Image.kf_imageWithCGImage(decompressedImageRef!, scale: scale, refImage: self)
  244. } else {
  245. return nil
  246. }
  247. }
  248. }
  249. // MARK: - Image format
  250. private let pngHeader: [UInt8] = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]
  251. private let jpgHeaderSOI: [UInt8] = [0xFF, 0xD8]
  252. private let jpgHeaderIF: [UInt8] = [0xFF]
  253. private let gifHeader: [UInt8] = [0x47, 0x49, 0x46]
  254. enum ImageFormat {
  255. case Unknown, PNG, JPEG, GIF
  256. }
  257. extension NSData {
  258. var kf_imageFormat: ImageFormat {
  259. var buffer = [UInt8](count: 8, repeatedValue: 0)
  260. self.getBytes(&buffer, length: 8)
  261. if buffer == pngHeader {
  262. return .PNG
  263. } else if buffer[0] == jpgHeaderSOI[0] &&
  264. buffer[1] == jpgHeaderSOI[1] &&
  265. buffer[2] == jpgHeaderIF[0]
  266. {
  267. return .JPEG
  268. } else if buffer[0] == gifHeader[0] &&
  269. buffer[1] == gifHeader[1] &&
  270. buffer[2] == gifHeader[2]
  271. {
  272. return .GIF
  273. }
  274. return .Unknown
  275. }
  276. }