Jacobo Koenig
Jacobo Koenig

Reputation: 12514

Making a GIF from images using Swift (macOS)

I was wondering if there was a way to convert an array of NSImages using Swift in macOS/osx?

I should be able to export it to file afterwards, so an animation of images displayed on my app would not be enough.

Thanks!

Upvotes: 3

Views: 2084

Answers (1)

Code Different
Code Different

Reputation: 93181

Image I/O has the functionalities you need. Try this:

var images = ... // init your array of NSImage

let destinationURL = NSURL(fileURLWithPath: "/path/to/image.gif")
let destinationGIF = CGImageDestinationCreateWithURL(destinationURL, kUTTypeGIF, images.count, nil)!

// The final size of your GIF. This is an optional parameter
var rect = NSMakeRect(0, 0, 350, 250)

// This dictionary controls the delay between frames
// If you don't specify this, CGImage will apply a default delay
let properties = [
    (kCGImagePropertyGIFDictionary as String): [(kCGImagePropertyGIFDelayTime as String): 1.0/16.0]
]


for img in images {
    // Convert an NSImage to CGImage, fitting within the specified rect
    // You can replace `&rect` with nil
    let cgImage = img.CGImageForProposedRect(&rect, context: nil, hints: nil)!

    // Add the frame to the GIF image
    // You can replace `properties` with nil
    CGImageDestinationAddImage(destinationGIF, cgImage, properties)
}

// Write the GIF file to disk
CGImageDestinationFinalize(destinationGIF)

Upvotes: 7

Related Questions