Image.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  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. 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. if frameCount == 1 {
  178. // Single frame
  179. gifDuration = Double.infinity
  180. } else {
  181. // Animated GIF
  182. guard let properties = CGImageSourceCopyPropertiesAtIndex(imageSource, i, nil),
  183. gifInfo = (properties as NSDictionary)[kCGImagePropertyGIFDictionary as String] as? NSDictionary,
  184. frameDuration = (gifInfo[kCGImagePropertyGIFDelayTime as String] as? NSNumber) else
  185. {
  186. return nil
  187. }
  188. gifDuration += frameDuration.doubleValue
  189. }
  190. images.append(Image.kf_imageWithCGImage(imageRef, scale: scale, refImage: nil))
  191. }
  192. #if os(OSX)
  193. if let image = Image(data: data) {
  194. image.kf_images = images
  195. image.kf_duration = gifDuration
  196. return image
  197. }
  198. return nil
  199. #else
  200. return Image.kf_animatedImageWithImages(images, duration: duration <= 0.0 ? gifDuration : duration)
  201. #endif
  202. }
  203. }
  204. // MARK: - Create images from data
  205. extension Image {
  206. static func kf_imageWithData(data: NSData, scale: CGFloat) -> Image? {
  207. var image: Image?
  208. #if os(OSX)
  209. switch data.kf_imageFormat {
  210. case .JPEG: image = Image(data: data)
  211. case .PNG: image = Image(data: data)
  212. case .GIF: image = Image.kf_animatedImageWithGIFData(gifData: data, scale: scale, duration: 0.0)
  213. case .Unknown: image = nil
  214. }
  215. #else
  216. switch data.kf_imageFormat {
  217. case .JPEG: image = Image(data: data, scale: scale)
  218. case .PNG: image = Image(data: data, scale: scale)
  219. case .GIF: image = Image.kf_animatedImageWithGIFData(gifData: data, scale: scale, duration: 0.0)
  220. case .Unknown: image = nil
  221. }
  222. #endif
  223. return image
  224. }
  225. }
  226. // MARK: - Decode
  227. extension Image {
  228. func kf_decodedImage() -> Image? {
  229. return self.kf_decodedImage(scale: kf_scale)
  230. }
  231. func kf_decodedImage(scale scale: CGFloat) -> Image? {
  232. // prevent animated image (GIF) lose it's images
  233. if kf_images != nil {
  234. return self
  235. }
  236. let imageRef = self.CGImage
  237. let colorSpace = CGColorSpaceCreateDeviceRGB()
  238. let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedLast.rawValue).rawValue
  239. let contextHolder = UnsafeMutablePointer<Void>()
  240. let context = CGBitmapContextCreate(contextHolder, CGImageGetWidth(imageRef), CGImageGetHeight(imageRef), 8, 0, colorSpace, bitmapInfo)
  241. if let context = context {
  242. let rect = CGRect(x: 0, y: 0, width: CGImageGetWidth(imageRef), height: CGImageGetHeight(imageRef))
  243. CGContextDrawImage(context, rect, imageRef)
  244. let decompressedImageRef = CGBitmapContextCreateImage(context)
  245. return Image.kf_imageWithCGImage(decompressedImageRef!, scale: scale, refImage: self)
  246. } else {
  247. return nil
  248. }
  249. }
  250. }
  251. // MARK: - Image format
  252. private let pngHeader: [UInt8] = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]
  253. private let jpgHeaderSOI: [UInt8] = [0xFF, 0xD8]
  254. private let jpgHeaderIF: [UInt8] = [0xFF]
  255. private let gifHeader: [UInt8] = [0x47, 0x49, 0x46]
  256. enum ImageFormat {
  257. case Unknown, PNG, JPEG, GIF
  258. }
  259. extension NSData {
  260. var kf_imageFormat: ImageFormat {
  261. var buffer = [UInt8](count: 8, repeatedValue: 0)
  262. self.getBytes(&buffer, length: 8)
  263. if buffer == pngHeader {
  264. return .PNG
  265. } else if buffer[0] == jpgHeaderSOI[0] &&
  266. buffer[1] == jpgHeaderSOI[1] &&
  267. buffer[2] == jpgHeaderIF[0]
  268. {
  269. return .JPEG
  270. } else if buffer[0] == gifHeader[0] &&
  271. buffer[1] == gifHeader[1] &&
  272. buffer[2] == gifHeader[2]
  273. {
  274. return .GIF
  275. }
  276. return .Unknown
  277. }
  278. }