Skip to content

Instantly share code, notes, and snippets.

@ScottBuchanan
Last active November 14, 2022 10:47
Show Gist options
  • Save ScottBuchanan/c63129cc2c5bb824fbac21c2d389ed22 to your computer and use it in GitHub Desktop.
Save ScottBuchanan/c63129cc2c5bb824fbac21c2d389ed22 to your computer and use it in GitHub Desktop.
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