通过 Swift 3.0 生成和导出动画 gif?

Generate and export an animated gif via Swift 3.0?

根据文档,我了解到图像 IO 框架自 iOS 9 以来在语法上发生了变化,但是我已经完成了我的研究和以下代码似乎是正确的。我必须执行下面列出的程序;一个过程拍摄图像并将这些图像作为 gif 格式写入应用程序的文档文件夹。我可以确认这是有效的,因为如果我使用 iTunes 转到应用程序的文档文件夹,我可以查看实际的 gif 文件。尽管如此,在我尝试从同一个文件读取的第二个过程中,抛出一个错误,指出该路径上的文件不存在。我已经在下面发布了代码。

class GifManager {
private func getDocumentsDirectory() -> URL?  {
    return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
}

public func generateGif(photos: [UIImage], filename: String) -> Bool {
    if let docsDirectory = getDocumentsDirectory() {
        let url = docsDirectory.appendingPathComponent(filename)
        let fileProperties = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFLoopCount as String: 0]]
        let gifProperties = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFDelayTime as String: 0.125]]
        if let destination = CGImageDestinationCreateWithURL(url as CFURL, kUTTypeGIF, photos.count, nil) {
            CGImageDestinationSetProperties(destination, fileProperties as CFDictionary?)
            for photo in photos {
                CGImageDestinationAddImage(destination, photo.cgImage!, gifProperties as CFDictionary?)
            }
            return CGImageDestinationFinalize(destination)
        }
    }
    return false
}

public func saveGifToCameraRoll(filename: String) {
    if let docsDirectory = getDocumentsDirectory() {
        let fileUrl: URL = docsDirectory.appendingPathComponent(filename)
        do {
            let data = try Data(contentsOf: fileUrl)
            if let _ = UIImage(data: data) {
                PHPhotoLibrary.shared().performChanges({
                    PHAssetChangeRequest.creationRequestForAssetFromImage(atFileURL: fileUrl)
                    }, completionHandler: {completed, error in
                        if error != nil {
                            print("error")
                        } else if completed {
                            print("completed")
                        } else {
                            print("not completed")
                        }
                })
            }

        } catch let error {
            print(error)
        }
    }
}

Swift 3.1、4 和 5

对于那些想要更新版本的 GIF 生成功能的人,我已经把它包含在这里了。

此函数需要 ImageIOMobileCoreServices 导入语句。

import ImageIO
import MobileCoreServices

这是函数。

func generateGif(photos: [UIImage], filename: String) -> Bool {
    let documentsDirectoryPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
    let path = documentsDirectoryPath.appending(filename)
    let fileProperties = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFLoopCount as String: 0]]
    let gifProperties = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFDelayTime as String: 0.125]]
    let cfURL = URL(fileURLWithPath: path) as CFURL
    if let destination = CGImageDestinationCreateWithURL(cfURL, kUTTypeGIF, photos.count, nil) {
            CGImageDestinationSetProperties(destination, fileProperties as CFDictionary?)
            for photo in photos {
                CGImageDestinationAddImage(destination, photo.cgImage!, gifProperties as CFDictionary?)
            }
            return CGImageDestinationFinalize(destination)
        }
    return false
}

编辑:

它有一个 Bool 所以你知道你可以安全地使用它创建的文件。

if generateGif(arrayOfImages, "/myGIFfile.gif") {
    // do something with gif
} else {
    // failed to create and close the gif file
}