added iOS source code
[wl-app.git] / iOS / Pods / Kingfisher / Sources / Image.swift
1 //
2 //  Image.swift
3 //  Kingfisher
4 //
5 //  Created by Wei Wang on 16/1/6.
6 //
7 //  Copyright (c) 2018 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
27
28 #if os(macOS)
29 import AppKit
30 private var imagesKey: Void?
31 private var durationKey: Void?
32 #else
33 import UIKit
34 import MobileCoreServices
35 private var imageSourceKey: Void?
36 #endif
37 private var animatedImageDataKey: Void?
38
39 import ImageIO
40 import CoreGraphics
41
42 #if !os(watchOS)
43 import Accelerate
44 import CoreImage
45 #endif
46
47 // MARK: - Image Properties
48 extension Kingfisher where Base: Image {
49     fileprivate(set) var animatedImageData: Data? {
50         get {
51             return objc_getAssociatedObject(base, &animatedImageDataKey) as? Data
52         }
53         set {
54             objc_setAssociatedObject(base, &animatedImageDataKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
55         }
56     }
57     
58     #if os(macOS)
59     var cgImage: CGImage? {
60         return base.cgImage(forProposedRect: nil, context: nil, hints: nil)
61     }
62     
63     var scale: CGFloat {
64         return 1.0
65     }
66     
67     fileprivate(set) var images: [Image]? {
68         get {
69             return objc_getAssociatedObject(base, &imagesKey) as? [Image]
70         }
71         set {
72             objc_setAssociatedObject(base, &imagesKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
73         }
74     }
75     
76     fileprivate(set) var duration: TimeInterval {
77         get {
78             return objc_getAssociatedObject(base, &durationKey) as? TimeInterval ?? 0.0
79         }
80         set {
81             objc_setAssociatedObject(base, &durationKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
82         }
83     }
84     
85     var size: CGSize {
86         return base.representations.reduce(CGSize.zero, { size, rep in
87             return CGSize(width: max(size.width, CGFloat(rep.pixelsWide)), height: max(size.height, CGFloat(rep.pixelsHigh)))
88         })
89     }
90     
91     #else
92     var cgImage: CGImage? {
93         return base.cgImage
94     }
95     
96     var scale: CGFloat {
97         return base.scale
98     }
99     
100     var images: [Image]? {
101         return base.images
102     }
103     
104     var duration: TimeInterval {
105         return base.duration
106     }
107     
108     fileprivate(set) var imageSource: ImageSource? {
109         get {
110             return objc_getAssociatedObject(base, &imageSourceKey) as? ImageSource
111         }
112         set {
113             objc_setAssociatedObject(base, &imageSourceKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
114         }
115     }
116     
117     var size: CGSize {
118         return base.size
119     }
120     #endif
121 }
122
123 // MARK: - Image Conversion
124 extension Kingfisher where Base: Image {
125     #if os(macOS)
126     static func image(cgImage: CGImage, scale: CGFloat, refImage: Image?) -> Image {
127         return Image(cgImage: cgImage, size: CGSize.zero)
128     }
129     
130     /**
131      Normalize the image. This method does nothing in OS X.
132      
133      - returns: The image itself.
134      */
135     public var normalized: Image {
136         return base
137     }
138     
139     static func animated(with images: [Image], forDuration forDurationduration: TimeInterval) -> Image? {
140         return nil
141     }
142     #else
143     static func image(cgImage: CGImage, scale: CGFloat, refImage: Image?) -> Image {
144         if let refImage = refImage {
145             return Image(cgImage: cgImage, scale: scale, orientation: refImage.imageOrientation)
146         } else {
147             return Image(cgImage: cgImage, scale: scale, orientation: .up)
148         }
149     }
150     
151     /**
152      Normalize the image. This method will try to redraw an image with orientation and scale considered.
153      
154      - returns: The normalized image with orientation set to up and correct scale.
155      */
156     public var normalized: Image {
157         // prevent animated image (GIF) lose it's images
158         guard images == nil else { return base }
159         // No need to do anything if already up
160         guard base.imageOrientation != .up else { return base }
161     
162         return draw(cgImage: nil, to: size) {
163             base.draw(in: CGRect(origin: CGPoint.zero, size: size))
164         }
165     }
166     
167     static func animated(with images: [Image], forDuration duration: TimeInterval) -> Image? {
168         return .animatedImage(with: images, duration: duration)
169     }
170     #endif
171 }
172
173 // MARK: - Image Representation
174 extension Kingfisher where Base: Image {
175     // MARK: - PNG
176     public func pngRepresentation() -> Data? {
177         #if os(macOS)
178             guard let cgimage = cgImage else {
179                 return nil
180             }
181             let rep = NSBitmapImageRep(cgImage: cgimage)
182             return rep.representation(using: .png, properties: [:])
183         #else
184             return UIImagePNGRepresentation(base)
185         #endif
186     }
187     
188     // MARK: - JPEG
189     public func jpegRepresentation(compressionQuality: CGFloat) -> Data? {
190         #if os(macOS)
191             guard let cgImage = cgImage else {
192                 return nil
193             }
194             let rep = NSBitmapImageRep(cgImage: cgImage)
195             return rep.representation(using:.jpeg, properties: [.compressionFactor: compressionQuality])
196         #else
197             return UIImageJPEGRepresentation(base, compressionQuality)
198         #endif
199     }
200     
201     // MARK: - GIF
202     public func gifRepresentation() -> Data? {
203         return animatedImageData
204     }
205 }
206
207 // MARK: - Create images from data
208 extension Kingfisher where Base: Image {
209     static func animated(with data: Data, scale: CGFloat = 1.0, duration: TimeInterval = 0.0, preloadAll: Bool, onlyFirstFrame: Bool = false) -> Image? {
210         
211         func decode(from imageSource: CGImageSource, for options: NSDictionary) -> ([Image], TimeInterval)? {
212             
213             //Calculates frame duration for a gif frame out of the kCGImagePropertyGIFDictionary dictionary
214             func frameDuration(from gifInfo: NSDictionary?) -> Double {
215                 let gifDefaultFrameDuration = 0.100
216                 
217                 guard let gifInfo = gifInfo else {
218                     return gifDefaultFrameDuration
219                 }
220                 
221                 let unclampedDelayTime = gifInfo[kCGImagePropertyGIFUnclampedDelayTime as String] as? NSNumber
222                 let delayTime = gifInfo[kCGImagePropertyGIFDelayTime as String] as? NSNumber
223                 let duration = unclampedDelayTime ?? delayTime
224                 
225                 guard let frameDuration = duration else { return gifDefaultFrameDuration }
226                 
227                 return frameDuration.doubleValue > 0.011 ? frameDuration.doubleValue : gifDefaultFrameDuration
228             }
229             
230             let frameCount = CGImageSourceGetCount(imageSource)
231             var images = [Image]()
232             var gifDuration = 0.0
233             for i in 0 ..< frameCount {
234                 
235                 guard let imageRef = CGImageSourceCreateImageAtIndex(imageSource, i, options) else {
236                     return nil
237                 }
238
239                 if frameCount == 1 {
240                     // Single frame
241                     gifDuration = Double.infinity
242                 } else {
243                     
244                     // Animated GIF
245                     guard let properties = CGImageSourceCopyPropertiesAtIndex(imageSource, i, nil) else {
246                         return nil
247                     }
248
249                     let gifInfo = (properties as NSDictionary)[kCGImagePropertyGIFDictionary as String] as? NSDictionary
250                     gifDuration += frameDuration(from: gifInfo)
251                 }
252                 
253                 images.append(Kingfisher<Image>.image(cgImage: imageRef, scale: scale, refImage: nil))
254                 
255                 if onlyFirstFrame { break }
256             }
257             
258             return (images, gifDuration)
259         }
260         
261         // Start of kf.animatedImageWithGIFData
262         let options: NSDictionary = [kCGImageSourceShouldCache as String: true, kCGImageSourceTypeIdentifierHint as String: kUTTypeGIF]
263         guard let imageSource = CGImageSourceCreateWithData(data as CFData, options) else {
264             return nil
265         }
266         
267         #if os(macOS)
268             guard let (images, gifDuration) = decode(from: imageSource, for: options) else {
269                 return nil
270             }
271             let image: Image?
272             if onlyFirstFrame {
273                 image = images.first
274             } else {
275                 image = Image(data: data)
276                 image?.kf.images = images
277                 image?.kf.duration = gifDuration
278             }
279             image?.kf.animatedImageData = data
280             return image
281         #else
282             
283             let image: Image?
284             if preloadAll || onlyFirstFrame {
285                 guard let (images, gifDuration) = decode(from: imageSource, for: options) else { return nil }
286                 image = onlyFirstFrame ? images.first : Kingfisher<Image>.animated(with: images, forDuration: duration <= 0.0 ? gifDuration : duration)
287             } else {
288                 image = Image(data: data)
289                 image?.kf.imageSource = ImageSource(ref: imageSource)
290             }
291             image?.kf.animatedImageData = data
292             return image
293         #endif
294     }
295
296     static func image(data: Data, scale: CGFloat, preloadAllAnimationData: Bool, onlyFirstFrame: Bool) -> Image? {
297         var image: Image?
298
299         #if os(macOS)
300             switch data.kf.imageFormat {
301             case .JPEG:
302                 image = Image(data: data)
303             case .PNG:
304                 image = Image(data: data)
305             case .GIF:
306                 image = Kingfisher<Image>.animated(
307                     with: data,
308                     scale: scale,
309                     duration: 0.0,
310                     preloadAll: preloadAllAnimationData,
311                     onlyFirstFrame: onlyFirstFrame)
312             case .unknown:
313                 image = Image(data: data)
314             }
315         #else
316             switch data.kf.imageFormat {
317             case .JPEG:
318                 image = Image(data: data, scale: scale)
319             case .PNG:
320                 image = Image(data: data, scale: scale)
321             case .GIF:
322                 image = Kingfisher<Image>.animated(
323                     with: data,
324                     scale: scale,
325                     duration: 0.0,
326                     preloadAll: preloadAllAnimationData,
327                     onlyFirstFrame: onlyFirstFrame)
328             case .unknown:
329                 image = Image(data: data, scale: scale)
330             }
331         #endif
332
333         return image
334     }
335 }
336
337 // MARK: - Image Transforming
338 extension Kingfisher where Base: Image {
339     // MARK: - Blend Mode
340     /// Create image based on `self` and apply blend mode.
341     ///
342     /// - parameter blendMode:       The blend mode of creating image.
343     /// - parameter alpha:           The alpha should be used for image.
344     /// - parameter backgroundColor: The background color for the output image.
345     ///
346     /// - returns: An image with blend mode applied.
347     ///
348     /// - Note: This method only works for CG-based image.
349     #if !os(macOS)
350     public func image(withBlendMode blendMode: CGBlendMode,
351                       alpha: CGFloat = 1.0,
352                       backgroundColor: Color? = nil) -> Image
353     {
354         guard let cgImage = cgImage else {
355             assertionFailure("[Kingfisher] Blend mode image only works for CG-based image.")
356             return base
357         }
358
359         let rect = CGRect(origin: .zero, size: size)
360         return draw(cgImage: cgImage, to: rect.size) {
361             if let backgroundColor = backgroundColor {
362                 backgroundColor.setFill()
363                 UIRectFill(rect)
364             }
365
366             base.draw(in: rect, blendMode: blendMode, alpha: alpha)
367         }
368     }
369     #endif
370
371     // MARK: - Compositing Operation
372     /// Create image based on `self` and apply compositing operation.
373     ///
374     /// - parameter compositingOperation: The compositing operation of creating image.
375     /// - parameter alpha:                The alpha should be used for image.
376     /// - parameter backgroundColor:      The background color for the output image.
377     ///
378     /// - returns: An image with compositing operation applied.
379     ///
380     /// - Note: This method only works for CG-based image.
381     #if os(macOS)
382     public func image(withCompositingOperation compositingOperation: NSCompositingOperation,
383                       alpha: CGFloat = 1.0,
384                       backgroundColor: Color? = nil) -> Image
385     {
386         guard let cgImage = cgImage else {
387             assertionFailure("[Kingfisher] Compositing Operation image only works for CG-based image.")
388             return base
389         }
390
391         let rect = CGRect(origin: .zero, size: size)
392         return draw(cgImage: cgImage, to: rect.size) {
393             if let backgroundColor = backgroundColor {
394                 backgroundColor.setFill()
395                 rect.fill()
396             }
397
398             base.draw(in: rect, from: NSRect.zero, operation: compositingOperation, fraction: alpha)
399         }
400     }
401     #endif
402
403     // MARK: - Round Corner
404     /// Create a round corner image based on `self`.
405     ///
406     /// - parameter radius:          The round corner radius of creating image.
407     /// - parameter size:            The target size of creating image.
408     /// - parameter corners:         The target corners which will be applied rounding.
409     /// - parameter backgroundColor: The background color for the output image
410     ///
411     /// - returns: An image with round corner of `self`.
412     ///
413     /// - Note: This method only works for CG-based image.
414     public func image(withRoundRadius radius: CGFloat,
415                       fit size: CGSize,
416                       roundingCorners corners: RectCorner = .all,
417                       backgroundColor: Color? = nil) -> Image
418     {   
419         guard let cgImage = cgImage else {
420             assertionFailure("[Kingfisher] Round corner image only works for CG-based image.")
421             return base
422         }
423         
424         let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
425         return draw(cgImage: cgImage, to: size) {
426             #if os(macOS)
427                 if let backgroundColor = backgroundColor {
428                     let rectPath = NSBezierPath(rect: rect)
429                     backgroundColor.setFill()
430                     rectPath.fill()
431                 }
432
433                 let path = NSBezierPath(roundedRect: rect, byRoundingCorners: corners, radius: radius)
434                 path.windingRule = .evenOddWindingRule
435                 path.addClip()
436                 base.draw(in: rect)
437             #else
438                 guard let context = UIGraphicsGetCurrentContext() else {
439                     assertionFailure("[Kingfisher] Failed to create CG context for image.")
440                     return
441                 }
442
443                 if let backgroundColor = backgroundColor {
444                     let rectPath = UIBezierPath(rect: rect)
445                     backgroundColor.setFill()
446                     rectPath.fill()
447                 }
448
449                 let path = UIBezierPath(roundedRect: rect,
450                                         byRoundingCorners: corners.uiRectCorner,
451                                         cornerRadii: CGSize(width: radius, height: radius)).cgPath
452                 context.addPath(path)
453                 context.clip()
454                 base.draw(in: rect)
455             #endif
456         }
457     }
458     
459     #if os(iOS) || os(tvOS)
460     func resize(to size: CGSize, for contentMode: UIViewContentMode) -> Image {
461         switch contentMode {
462         case .scaleAspectFit:
463             return resize(to: size, for: .aspectFit)
464         case .scaleAspectFill:
465             return resize(to: size, for: .aspectFill)
466         default:
467             return resize(to: size)
468         }
469     }
470     #endif
471     
472     // MARK: - Resize
473     /// Resize `self` to an image of new size.
474     ///
475     /// - parameter size: The target size.
476     ///
477     /// - returns: An image with new size.
478     ///
479     /// - Note: This method only works for CG-based image.
480     public func resize(to size: CGSize) -> Image {
481         
482         guard let cgImage = cgImage else {
483             assertionFailure("[Kingfisher] Resize only works for CG-based image.")
484             return base
485         }
486         
487         let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
488         return draw(cgImage: cgImage, to: size) {
489             #if os(macOS)
490                 base.draw(in: rect, from: NSRect.zero, operation: .copy, fraction: 1.0)
491             #else
492                 base.draw(in: rect)
493             #endif
494         }
495     }
496     
497     /// Resize `self` to an image of new size, respecting the content mode.
498     ///
499     /// - Parameters:
500     ///   - size: The target size.
501     ///   - contentMode: Content mode of output image should be.
502     /// - Returns: An image with new size.
503     public func resize(to size: CGSize, for contentMode: ContentMode) -> Image {
504         switch contentMode {
505         case .aspectFit:
506             let newSize = self.size.kf.constrained(size)
507             return resize(to: newSize)
508         case .aspectFill:
509             let newSize = self.size.kf.filling(size)
510             return resize(to: newSize)
511         default:
512             return resize(to: size)
513         }
514     }
515     
516     public func crop(to size: CGSize, anchorOn anchor: CGPoint) -> Image {
517         guard let cgImage = cgImage else {
518             assertionFailure("[Kingfisher] Crop only works for CG-based image.")
519             return base
520         }
521         
522         let rect = self.size.kf.constrainedRect(for: size, anchor: anchor)
523         guard let image = cgImage.cropping(to: rect.scaled(scale)) else {
524             assertionFailure("[Kingfisher] Cropping image failed.")
525             return base
526         }
527         
528         return Kingfisher.image(cgImage: image, scale: scale, refImage: base)
529     }
530     
531     // MARK: - Blur
532     
533     /// Create an image with blur effect based on `self`.
534     ///
535     /// - parameter radius: The blur radius should be used when creating blur effect.
536     ///
537     /// - returns: An image with blur effect applied.
538     ///
539     /// - Note: This method only works for CG-based image.
540     public func blurred(withRadius radius: CGFloat) -> Image {
541         #if os(watchOS)
542             return base
543         #else
544             guard let cgImage = cgImage else {
545                 assertionFailure("[Kingfisher] Blur only works for CG-based image.")
546                 return base
547             }
548             
549             // http://www.w3.org/TR/SVG/filters.html#feGaussianBlurElement
550             // let d = floor(s * 3*sqrt(2*pi)/4 + 0.5)
551             // if d is odd, use three box-blurs of size 'd', centered on the output pixel.
552             let s = Float(max(radius, 2.0))
553             // We will do blur on a resized image (*0.5), so the blur radius could be half as well.
554             
555             // Fix the slow compiling time for Swift 3. 
556             // See https://github.com/onevcat/Kingfisher/issues/611
557             let pi2 = 2 * Float.pi
558             let sqrtPi2 = sqrt(pi2)
559             var targetRadius = floor(s * 3.0 * sqrtPi2 / 4.0 + 0.5)
560             
561             if targetRadius.isEven {
562                 targetRadius += 1
563             }
564             
565             let iterations: Int
566             if radius < 0.5 {
567                 iterations = 1
568             } else if radius < 1.5 {
569                 iterations = 2
570             } else {
571                 iterations = 3
572             }
573             
574             let w = Int(size.width)
575             let h = Int(size.height)
576             let rowBytes = Int(CGFloat(cgImage.bytesPerRow))
577             
578             func createEffectBuffer(_ context: CGContext) -> vImage_Buffer {
579                 let data = context.data
580                 let width = vImagePixelCount(context.width)
581                 let height = vImagePixelCount(context.height)
582                 let rowBytes = context.bytesPerRow
583                 
584                 return vImage_Buffer(data: data, height: height, width: width, rowBytes: rowBytes)
585             }
586
587             guard let context = beginContext(size: size, scale: scale) else {
588                 assertionFailure("[Kingfisher] Failed to create CG context for blurring image.")
589                 return base
590             }
591             defer { endContext() }
592
593             context.draw(cgImage, in: CGRect(x: 0, y: 0, width: w, height: h))
594             
595             var inBuffer = createEffectBuffer(context)
596             
597             guard let outContext = beginContext(size: size, scale: scale) else {
598                 assertionFailure("[Kingfisher] Failed to create CG context for blurring image.")
599                 return base
600             }
601             defer { endContext() }
602             var outBuffer = createEffectBuffer(outContext)
603             
604             for _ in 0 ..< iterations {
605                 vImageBoxConvolve_ARGB8888(&inBuffer, &outBuffer, nil, 0, 0, UInt32(targetRadius), UInt32(targetRadius), nil, vImage_Flags(kvImageEdgeExtend))
606                 (inBuffer, outBuffer) = (outBuffer, inBuffer)
607             }
608             
609             #if os(macOS)
610                 let result = outContext.makeImage().flatMap { fixedForRetinaPixel(cgImage: $0, to: size) }
611             #else
612                 let result = outContext.makeImage().flatMap { Image(cgImage: $0, scale: base.scale, orientation: base.imageOrientation) }
613             #endif
614             guard let blurredImage = result else {
615                 assertionFailure("[Kingfisher] Can not make an blurred image within this context.")
616                 return base
617             }
618             
619             return blurredImage
620         #endif
621     }
622     
623     // MARK: - Overlay
624     
625     /// Create an image from `self` with a color overlay layer.
626     ///
627     /// - parameter color:    The color should be use to overlay.
628     /// - parameter fraction: Fraction of input color. From 0.0 to 1.0. 0.0 means solid color, 1.0 means transparent overlay.
629     ///
630     /// - returns: An image with a color overlay applied.
631     ///
632     /// - Note: This method only works for CG-based image.
633     public func overlaying(with color: Color, fraction: CGFloat) -> Image {
634         
635         guard let cgImage = cgImage else {
636             assertionFailure("[Kingfisher] Overlaying only works for CG-based image.")
637             return base
638         }
639         
640         let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
641         return draw(cgImage: cgImage, to: rect.size) {
642             #if os(macOS)
643                 base.draw(in: rect)
644                 if fraction > 0 {
645                     color.withAlphaComponent(1 - fraction).set()
646                     rect.fill(using: .sourceAtop)
647                 }
648             #else
649                 color.set()
650                 UIRectFill(rect)
651                 base.draw(in: rect, blendMode: .destinationIn, alpha: 1.0)
652                 
653                 if fraction > 0 {
654                     base.draw(in: rect, blendMode: .sourceAtop, alpha: fraction)
655                 }
656             #endif
657         }
658     }
659     
660     // MARK: - Tint
661     
662     /// Create an image from `self` with a color tint.
663     ///
664     /// - parameter color: The color should be used to tint `self`
665     ///
666     /// - returns: An image with a color tint applied.
667     public func tinted(with color: Color) -> Image {
668         #if os(watchOS)
669             return base
670         #else
671             return apply(.tint(color))
672         #endif
673     }
674     
675     // MARK: - Color Control
676     
677     /// Create an image from `self` with color control.
678     ///
679     /// - parameter brightness: Brightness changing to image.
680     /// - parameter contrast:   Contrast changing to image.
681     /// - parameter saturation: Saturation changing to image.
682     /// - parameter inputEV:    InputEV changing to image.
683     ///
684     /// - returns: An image with color control applied.
685     public func adjusted(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) -> Image {
686         #if os(watchOS)
687             return base
688         #else
689             return apply(.colorControl((brightness, contrast, saturation, inputEV)))
690         #endif
691     }
692
693     /// Return an image with given scale.
694     ///
695     /// - Parameter scale: Target scale factor the new image should have.
696     /// - Returns: The image with target scale. If the base image is already in the scale, `base` will be returned.
697     public func scaled(to scale: CGFloat) -> Image {
698         guard scale != self.scale else {
699             return base
700         }
701         guard let cgImage = cgImage else {
702             assertionFailure("[Kingfisher] Scaling only works for CG-based image.")
703             return base
704         }
705         return Kingfisher.image(cgImage: cgImage, scale: scale, refImage: base)
706     }
707 }
708
709 // MARK: - Decode
710 extension Kingfisher where Base: Image {
711     var decoded: Image {
712         return decoded(scale: scale)
713     }
714     
715     func decoded(scale: CGFloat) -> Image {
716         // prevent animated image (GIF) lose it's images
717         #if os(iOS)
718             if imageSource != nil { return base }
719         #else
720             if images != nil { return base }
721         #endif
722         
723         guard let imageRef = self.cgImage else {
724             assertionFailure("[Kingfisher] Decoding only works for CG-based image.")
725             return base
726         }
727         
728         // Draw CGImage in a plain context with scale of 1.0.
729         guard let context = beginContext(size: CGSize(width: imageRef.width, height: imageRef.height), scale: 1.0) else {
730             assertionFailure("[Kingfisher] Decoding fails to create a valid context.")
731             return base
732         }
733         
734         defer { endContext() }
735         
736         let rect = CGRect(x: 0, y: 0, width: CGFloat(imageRef.width), height: CGFloat(imageRef.height))
737         context.draw(imageRef, in: rect)
738         let decompressedImageRef = context.makeImage()
739         return Kingfisher<Image>.image(cgImage: decompressedImageRef!, scale: scale, refImage: base)
740     }
741 }
742
743 /// Reference the source image reference
744 final class ImageSource {
745     var imageRef: CGImageSource?
746     init(ref: CGImageSource) {
747         self.imageRef = ref
748     }
749 }
750
751 // MARK: - Image format
752 private struct ImageHeaderData {
753     static var PNG: [UInt8] = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]
754     static var JPEG_SOI: [UInt8] = [0xFF, 0xD8]
755     static var JPEG_IF: [UInt8] = [0xFF]
756     static var GIF: [UInt8] = [0x47, 0x49, 0x46]
757 }
758
759 enum ImageFormat {
760     case unknown, PNG, JPEG, GIF
761 }
762
763
764 // MARK: - Misc Helpers
765 public struct DataProxy {
766     fileprivate let base: Data
767     init(proxy: Data) {
768         base = proxy
769     }
770 }
771
772 extension Data: KingfisherCompatible {
773     public typealias CompatibleType = DataProxy
774     public var kf: DataProxy {
775         return DataProxy(proxy: self)
776     }
777 }
778
779 extension DataProxy {
780     var imageFormat: ImageFormat {
781         var buffer = [UInt8](repeating: 0, count: 8)
782         (base as NSData).getBytes(&buffer, length: 8)
783         if buffer == ImageHeaderData.PNG {
784             return .PNG
785         } else if buffer[0] == ImageHeaderData.JPEG_SOI[0] &&
786             buffer[1] == ImageHeaderData.JPEG_SOI[1] &&
787             buffer[2] == ImageHeaderData.JPEG_IF[0]
788         {
789             return .JPEG
790         } else if buffer[0] == ImageHeaderData.GIF[0] &&
791             buffer[1] == ImageHeaderData.GIF[1] &&
792             buffer[2] == ImageHeaderData.GIF[2]
793         {
794             return .GIF
795         }
796
797         return .unknown
798     }
799 }
800
801 public struct CGSizeProxy {
802     fileprivate let base: CGSize
803     init(proxy: CGSize) {
804         base = proxy
805     }
806 }
807
808 extension CGSize: KingfisherCompatible {
809     public typealias CompatibleType = CGSizeProxy
810     public var kf: CGSizeProxy {
811         return CGSizeProxy(proxy: self)
812     }
813 }
814
815 extension CGSizeProxy {
816     func constrained(_ size: CGSize) -> CGSize {
817         let aspectWidth = round(aspectRatio * size.height)
818         let aspectHeight = round(size.width / aspectRatio)
819
820         return aspectWidth > size.width ? CGSize(width: size.width, height: aspectHeight) : CGSize(width: aspectWidth, height: size.height)
821     }
822
823     func filling(_ size: CGSize) -> CGSize {
824         let aspectWidth = round(aspectRatio * size.height)
825         let aspectHeight = round(size.width / aspectRatio)
826
827         return aspectWidth < size.width ? CGSize(width: size.width, height: aspectHeight) : CGSize(width: aspectWidth, height: size.height)
828     }
829
830     private var aspectRatio: CGFloat {
831         return base.height == 0.0 ? 1.0 : base.width / base.height
832     }
833     
834     
835     func constrainedRect(for size: CGSize, anchor: CGPoint) -> CGRect {
836         
837         let unifiedAnchor = CGPoint(x: anchor.x.clamped(to: 0.0...1.0),
838                                     y: anchor.y.clamped(to: 0.0...1.0))
839         
840         let x = unifiedAnchor.x * base.width - unifiedAnchor.x * size.width
841         let y = unifiedAnchor.y * base.height - unifiedAnchor.y * size.height
842         let r = CGRect(x: x, y: y, width: size.width, height: size.height)
843         
844         let ori = CGRect(origin: CGPoint.zero, size: base)
845         return ori.intersection(r)
846     }
847 }
848
849 extension CGRect {
850     func scaled(_ scale: CGFloat) -> CGRect {
851         return CGRect(x: origin.x * scale, y: origin.y * scale,
852                       width: size.width * scale, height: size.height * scale)
853     }
854 }
855
856 extension Comparable {
857     func clamped(to limits: ClosedRange<Self>) -> Self {
858         return min(max(self, limits.lowerBound), limits.upperBound)
859     }
860 }
861
862 extension Kingfisher where Base: Image {
863     
864     func beginContext(size: CGSize, scale: CGFloat) -> CGContext? {
865         #if os(macOS)
866             guard let rep = NSBitmapImageRep(
867                 bitmapDataPlanes: nil,
868                 pixelsWide: Int(size.width),
869                 pixelsHigh: Int(size.height),
870                 bitsPerSample: cgImage?.bitsPerComponent ?? 8,
871                 samplesPerPixel: 4,
872                 hasAlpha: true,
873                 isPlanar: false,
874                 colorSpaceName: .calibratedRGB,
875                 bytesPerRow: 0,
876                 bitsPerPixel: 0) else
877             {
878                 assertionFailure("[Kingfisher] Image representation cannot be created.")
879                 return nil
880             }
881             rep.size = size
882             NSGraphicsContext.saveGraphicsState()
883             guard let context = NSGraphicsContext(bitmapImageRep: rep) else {
884                 assertionFailure("[Kingfisher] Image contenxt cannot be created.")
885                 return nil
886             }
887             
888             NSGraphicsContext.current = context
889             return context.cgContext
890         #else
891             UIGraphicsBeginImageContextWithOptions(size, false, scale)
892             let context = UIGraphicsGetCurrentContext()
893             context?.scaleBy(x: 1.0, y: -1.0)
894             context?.translateBy(x: 0, y: -size.height)
895             return context
896         #endif
897     }
898     
899     func endContext() {
900         #if os(macOS)
901             NSGraphicsContext.restoreGraphicsState()
902         #else
903             UIGraphicsEndImageContext()
904         #endif
905     }
906     
907     func draw(cgImage: CGImage?, to size: CGSize, draw: ()->()) -> Image {
908         #if os(macOS)
909         guard let rep = NSBitmapImageRep(
910             bitmapDataPlanes: nil,
911             pixelsWide: Int(size.width),
912             pixelsHigh: Int(size.height),
913             bitsPerSample: cgImage?.bitsPerComponent ?? 8,
914             samplesPerPixel: 4,
915             hasAlpha: true,
916             isPlanar: false,
917             colorSpaceName: .calibratedRGB,
918             bytesPerRow: 0,
919             bitsPerPixel: 0) else
920         {
921             assertionFailure("[Kingfisher] Image representation cannot be created.")
922             return base
923         }
924         rep.size = size
925         
926         NSGraphicsContext.saveGraphicsState()
927         
928         let context = NSGraphicsContext(bitmapImageRep: rep)
929         NSGraphicsContext.current = context
930         draw()
931         NSGraphicsContext.restoreGraphicsState()
932         
933         let outputImage = Image(size: size)
934         outputImage.addRepresentation(rep)
935         return outputImage
936         #else
937             
938         UIGraphicsBeginImageContextWithOptions(size, false, scale)
939         defer { UIGraphicsEndImageContext() }
940         draw()
941         return UIGraphicsGetImageFromCurrentImageContext() ?? base
942         
943         #endif
944     }
945     
946     #if os(macOS)
947     func fixedForRetinaPixel(cgImage: CGImage, to size: CGSize) -> Image {
948         
949         let image = Image(cgImage: cgImage, size: base.size)
950         let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
951         
952         return draw(cgImage: cgImage, to: self.size) {
953             image.draw(in: rect, from: NSRect.zero, operation: .copy, fraction: 1.0)
954         }
955     }
956     #endif
957 }
958
959 extension Float {
960     var isEven: Bool {
961         return truncatingRemainder(dividingBy: 2.0) == 0
962     }
963 }
964
965 #if os(macOS)
966 extension NSBezierPath {
967     convenience init(roundedRect rect: NSRect, topLeftRadius: CGFloat, topRightRadius: CGFloat,
968          bottomLeftRadius: CGFloat, bottomRightRadius: CGFloat)
969     {
970         self.init()
971         
972         let maxCorner = min(rect.width, rect.height) / 2
973         
974         let radiusTopLeft = min(maxCorner, max(0, topLeftRadius))
975         let radiustopRight = min(maxCorner, max(0, topRightRadius))
976         let radiusbottomLeft = min(maxCorner, max(0, bottomLeftRadius))
977         let radiusbottomRight = min(maxCorner, max(0, bottomRightRadius))
978         
979         guard !NSIsEmptyRect(rect) else {
980             return
981         }
982         
983         let topLeft = NSMakePoint(NSMinX(rect), NSMaxY(rect));
984         let topRight = NSMakePoint(NSMaxX(rect), NSMaxY(rect));
985         let bottomRight = NSMakePoint(NSMaxX(rect), NSMinY(rect));
986         
987         move(to: NSMakePoint(NSMidX(rect), NSMaxY(rect)))
988         appendArc(from: topLeft, to: rect.origin, radius: radiusTopLeft)
989         appendArc(from: rect.origin, to: bottomRight, radius: radiusbottomLeft)
990         appendArc(from: bottomRight, to: topRight, radius: radiusbottomRight)
991         appendArc(from: topRight, to: topLeft, radius: radiustopRight)
992         close()
993     }
994     
995     convenience init(roundedRect rect: NSRect, byRoundingCorners corners: RectCorner, radius: CGFloat) {
996         let radiusTopLeft = corners.contains(.topLeft) ? radius : 0
997         let radiusTopRight = corners.contains(.topRight) ? radius : 0
998         let radiusBottomLeft = corners.contains(.bottomLeft) ? radius : 0
999         let radiusBottomRight = corners.contains(.bottomRight) ? radius : 0
1000         
1001         self.init(roundedRect: rect, topLeftRadius: radiusTopLeft, topRightRadius: radiusTopRight,
1002                   bottomLeftRadius: radiusBottomLeft, bottomRightRadius: radiusBottomRight)
1003     }
1004 }
1005     
1006 #else
1007 extension RectCorner {
1008     var uiRectCorner: UIRectCorner {
1009         
1010         var result: UIRectCorner = []
1011         
1012         if self.contains(.topLeft) { result.insert(.topLeft) }
1013         if self.contains(.topRight) { result.insert(.topRight) }
1014         if self.contains(.bottomLeft) { result.insert(.bottomLeft) }
1015         if self.contains(.bottomRight) { result.insert(.bottomRight) }
1016         
1017         return result
1018     }
1019 }
1020 #endif
1021