Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 952
Jacobo Koenig Avatar asked Dec 05 '25 07:12

Jacobo Koenig


1 Answers

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)
like image 116
Code Different Avatar answered Dec 07 '25 23:12

Code Different



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!