Pregunta

I need to do some processing on the individual frames of an animated GIF so I need to be able to split an animated GIF, do some processing and merge it back again into a GIF.

I know how to create an animated gif from separate UIImages but I don't know how to split the frames of a GIF into separate UIImages.

Could anyone share some code that can do this?

¿Fue útil?

Solución

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.

Otros consejos

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
}

If you like Swift 3 solution, you can use Decoder from GifMagic https://github.com/onmyway133/GifMagic, which lets you access individual frame within the gif, and get additional gif infos, like size and delay time

let result = Decoder().decode(fileUrl: gifFileUrl)
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top