使用Swift(macOS)从图像制作GIF

3

我在想是否有办法使用Swift在macOS/OSX中将NSImages数组转换为其他格式?

之后我应该能够将其导出到文件,因此仅在我的应用程序上显示图像动画是不够的。

谢谢!


1
这取决于你所说的“有没有办法”的含义。从某种意义上来说,“有办法”是可以自己编写代码实现,但我认为在 Foundation 或 Cocoa 中并没有类似 NSGIF(imageSequence:) 的 API。 - zneak
我明白。你认为我能找到一个易于实现的库或示例代码吗? - Jacobo Koenig
实际上,您可能需要研究一下Image I/O框架(示例)。 - zneak
1个回答

7

Image I/O具有您需要的功能。尝试以下步骤:

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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接