How to split animated GIF into an array of UIImages?

You can use the Image I/O framework to load the frames of an animated GIF as individual CGImage objects, which you can then wrap in UIImage objects.

However, it would probably be much easier for you to just use my public domain UIImage+animatedGIF category to load the GIF into an animated UIImage, and then access the images property of the animated image to get the individual frames.


I would like to give an example for who want or need to see an example code (how to use this framework with this issue) written in Swift 4 for IOS :

static func getSequence(gifNamed: String) -> [UIImage]? {
    
    guard let bundleURL = Bundle.main
        .url(forResource: gifNamed, withExtension: "gif") else {
            print("This image named \"\(gifNamed)\" does not exist!")
            return nil
    }
    
    guard let imageData = try? Data(contentsOf: bundleURL) else {
        print("Cannot turn image named \"\(gifNamed)\" into NSData")
        return nil
    }
    
    let gifOptions = [
        kCGImageSourceShouldAllowFloat as String : true as NSNumber,
        kCGImageSourceCreateThumbnailWithTransform as String : true as NSNumber,
        kCGImageSourceCreateThumbnailFromImageAlways as String : true as NSNumber
        ] as CFDictionary
    
    guard let imageSource = CGImageSourceCreateWithData(imageData as CFData, gifOptions) else {
        debugPrint("Cannot create image source with data!")
        return nil
    }
    
    let framesCount = CGImageSourceGetCount(imageSource)
    var frameList = [UIImage]()
    
    for index in 0 ..< framesCount {
        
        if let cgImageRef = CGImageSourceCreateImageAtIndex(imageSource, index, nil) {
            let uiImageRef = UIImage(cgImage: cgImageRef)
            frameList.append(uiImageRef)
        }
        
    }
    
    return frameList // Your gif frames is ready
}