Swift – 从图像创build一个GIF并将其转换为NSData

这可能是一个业余爱好者的问题,但尽pipe我已经search堆栈溢出扩展,我没能得到我的具体问题的答案。

通过遵循Github示例,我成功地从一组图像创build了一个GIF文件:

func createGIF(with images: [NSImage], name: NSURL, loopCount: Int = 0, frameDelay: Double) { let destinationURL = name let destinationGIF = CGImageDestinationCreateWithURL(destinationURL, kUTTypeGIF, images.count, nil)! // 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): frameDelay] ] for img in images { // Convert an NSImage to CGImage, fitting within the specified rect let cgImage = img.CGImageForProposedRect(nil, context: nil, hints: nil)! // Add the frame to the GIF image CGImageDestinationAddImage(destinationGIF, cgImage, properties) } // Write the GIF file to disk CGImageDestinationFinalize(destinationGIF) } 

现在,我想将实际的GIF转换为NSData,以便将其上传到Firebase,并能够在其他设备上检索它。

为了实现我的目标,我有两个select:要么find如何使用上面的代码来提取创build的GIF(这似乎直接创build时创build文件),或使用函数的参数上的图像来创build一个新的GIF,但保持在NSData格式。

有没有人有任何想法如何做到这一点?

由于没有人超过六个月,我只会从@Sachin Vas的评论这里回答:

你可以使用NSData(contentsOf: URL)获得数据NSData(contentsOf: URL)