3

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!

Jacobo Koenig
  • 11,728
  • 9
  • 40
  • 75
  • 1
    It depends on what you mean by "is there a way". There "is a way" in the sense that you can code it yourself, but I don't think that there's any API that looks like `NSGIF(imageSequence:)` in Foundation or Cocoa. – zneak Aug 12 '16 at 18:37
  • I understand. Do you think I might be able to find an easy to implement library, or sample code? – Jacobo Koenig Aug 12 '16 at 18:43
  • Actually, you may want to look into the [Image I/O](https://developer.apple.com/library/mac/documentation/GraphicsImaging/Reference/ImageIORefCollection/index.html#//apple_ref/doc/uid/TP40005102) framework ([example](http://stackoverflow.com/questions/14915138/create-and-and-export-an-animated-gif-via-ios)). – zneak Aug 12 '16 at 18:47

1 Answers1

7

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)
Code Different
  • 90,614
  • 16
  • 144
  • 163