Last active
November 14, 2022 10:47
-
-
Save ScottBuchanan/c63129cc2c5bb824fbac21c2d389ed22 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Cocoa | |
struct ImageConstants { | |
static let gifDelayTime: NSNumber = 2 | |
static let gifLoopCount:NSNumber = 10 | |
} | |
extension NSImage { | |
//swift 2.0 translation/adaptation from https://gist.github.com/akisute/1141953 | |
//NSImage extension to export an array of NSImages to an animated gif at a given location | |
func exportAnimatedGif(toFilePath filePath: NSURL, withImages images: [NSImage]) -> Bool { | |
guard let fileDestination: CGImageDestination = CGImageDestinationCreateWithURL((filePath as CFURLRef), kUTTypeGIF, images.count, nil) else { | |
return false | |
} | |
let frameProperties = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFDelayTime as String: ImageConstants.gifDelayTime]] | |
let gifProperties = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFLoopCount as String: ImageConstants.gifLoopCount]] | |
for (_, image) in images.enumerate() { | |
let imageRef: CGImageRef = NSImage.makeCGImage(image) | |
CGImageDestinationAddImage(fileDestination, imageRef, (frameProperties as CFDictionaryRef)) | |
} | |
CGImageDestinationSetProperties(fileDestination, (gifProperties as CFDictionaryRef)) | |
CGImageDestinationFinalize(fileDestination) | |
return true | |
} | |
static func makeCGImage(image: NSImage)->CGImage { | |
var imageRect:CGRect = CGRectMake(0, 0, image.size.width, image.size.height) | |
return image.CGImageForProposedRect(&imageRect, context: nil, hints: nil)! | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment