Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 3: how to save Animated images from imageView (GIF)?

I am new to swift and I have some images that animated in one imageView, now I want to save it in gallery as we save simple image, How can I do that?

imageView.animationImages = [
            UIImage(named:"1.jpg")!,
            UIImage(named:"2.jpg")!,
            UIImage(named:"3.jpg")!,
            UIImage(named:"4.jpg")!,
            UIImage(named:"5.jpg")!
        ]

        imageView.animationDuration = 3
        imageView.startAnimating()

Any kind of Help will be appreciated...(:

like image 746
Sagar Aghara Avatar asked Dec 31 '25 15:12

Sagar Aghara


1 Answers

Refer the code here -> swift-create-a-gif-from-images-and-turn-it-into-nsdata

The above code is used for OS X, so I adjusted it a little bit.

Import ImageIO and MobileCoreServices

func createGIF(with images: [UIImage], name: URL, loopCount: Int = 0, frameDelay: Double) {

    let destinationURL = name
    let destinationGIF = CGImageDestinationCreateWithURL(destinationURL as CFURL, 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 UIImage to CGImage, fitting within the specified rect
        let cgImage = img.cgImage
        // Add the frame to the GIF image
        CGImageDestinationAddImage(destinationGIF, cgImage!, properties as CFDictionary?)
    }

    // Write the GIF file to disk
    CGImageDestinationFinalize(destinationGIF)
}

Use it in this way:

let documentsURL = FileManager.default.urls(for: .documentDirectory,
                                                   in: .userDomainMask).first
let path = documentsURL!.appendingPathComponent("1.gif")
createGIF(with: images, name: path, frameDelay: 0.1)
// you can check the path and open it in Finder, then you can see the file
print(path)

I also made a demo on github -> saveImagesAsGif

like image 138
XueYu Avatar answered Jan 03 '26 11:01

XueYu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!