- Those who are looking for a swifty answer to this question, here's an extension of UIImage that does the job.
import UIKit
import MobileCoreServices
extension UIImage {
func UIImageAnimatedGIFRepresentation(gifDuration: TimeInterval = 0.0, loopCount: Int = 0) throws -> Data {
let images = self.images ?? [self]
let frameCount = images.count
let frameDuration: TimeInterval = gifDuration <= 0.0 ? self.duration / Double(frameCount) : gifDuration / Double(frameCount)
let frameDelayCentiseconds = Int(lrint(frameDuration * 100))
let frameProperties = [
kCGImagePropertyGIFDictionary: [
kCGImagePropertyGIFDelayTime: NSNumber(value: frameDelayCentiseconds)
]
]
guard let mutableData = CFDataCreateMutable(nil, 0),
let destination = CGImageDestinationCreateWithData(mutableData, kUTTypeGIF, frameCount, nil) else {
throw NSError(domain: "AnimatedGIFSerializationErrorDomain",
code: -1,
userInfo: [NSLocalizedDescriptionKey: "Could not create destination with data."])
}
let imageProperties = [
kCGImagePropertyGIFDictionary: [kCGImagePropertyGIFLoopCount: NSNumber(value: loopCount)]
] as CFDictionary
CGImageDestinationSetProperties(destination, imageProperties)
for image in images {
if let cgimage = image.cgImage {
CGImageDestinationAddImage(destination, cgimage, frameProperties as CFDictionary)
}
}
let success = CGImageDestinationFinalize(destination)
if !success {
throw NSError(domain: "AnimatedGIFSerializationErrorDomain",
code: -2,
userInfo: [NSLocalizedDescriptionKey: "Could not finalize image destination"])
}
return mutableData as Data
}
}
- While the above extension will do the job, handling gif from image picker is simpler, here's the implementation in
UIImagePickerControllerDelegate
function.
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
let info = Dictionary(uniqueKeysWithValues: info.map {key, value in (key.rawValue, value)})
if let url = info[UIImagePickerController.InfoKey.referenceURL.rawValue] as? URL, url.pathExtension.lowercased() == "gif" {
picker.dismiss(animated: false, completion: nil)
url.getGifImageDataFromAssetUrl(completion: { imageData in
// Use imageData here.
})
return
}
}
with using an extension function in URL
import UIKit
import Photos
extension URL {
func getGifImageDataFromAssetUrl(completion: @escaping(_ imageData: Data?) -> Void) {
let asset = PHAsset.fetchAssets(withALAssetURLs: [self], options: nil)
if let image = asset.firstObject {
PHImageManager.default().requestImageData(for: image, options: nil) { (imageData, _, _, _) in
completion(imageData)
}
}
}
}