Swift - create GIF from images and turn it into NSData

This might be an amateur question, but although I was looking at Qaru extensibly, I was unable to get an answer on my specific problem.

I managed to create a GIF file from an array of images, following the example of Github:

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)
}

Now I would like to turn the actual GIF into NSData so that I can upload it to Firebase and get it on another device.

To achieve my goal, I have two options: either find how to use the above code to extract the created GIF (which seems to be directly created when creating the file), or use the images on the function parameters to create a new GIF, but save it in the format NSData.

Does anyone have any ideas on how to do this?

+4
1

, @Sachin Vas :

NSData(contentsOf: URL)

0

Source: https://habr.com/ru/post/1662668/


All Articles