Image.swift 12 KB

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