Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
615 views
in Technique[技术] by (71.8m points)

ios - How to load animated GIF from photo library

In iOS Swift I'm having difficulty loading an animated GIF from the device photo library to a UIImageView or creating a .gif file from it. I have no problem displaying the animated GIF if it's a file on a server or if it's right in the app. However, when I load it from the photo library, I lose the animation. I found some Objective-C solutions and tried to convert them over to Swift, but haven't had any luck.

Here is what I have so far:

@IBAction func buttonTapped(sender: UIButton) {
    selectPhoto()
}

func selectPhoto() {
    let photoLibraryController = UIImagePickerController()
    photoLibraryController.delegate = self
    photoLibraryController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary

    let mediaTypes:[String] = [kUTTypeImage as String]
    photoLibraryController.mediaTypes = mediaTypes
    photoLibraryController.allowsEditing = false

    self.presentViewController(photoLibraryController, animated: true, completion: nil)
}

// UIImagePickerControllerDelegate
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
    let origImage = info[UIImagePickerControllerOriginalImage] as! UIImage

    self.imageView.image = origImage

    picker.dismissViewControllerAnimated(true, completion: nil)

}

Optimally, I would like to save the photo library image to a gif file on the server. From there I have no trouble displaying it. However, I need some help getting the data from the photo library into some type of property, without losing the animation. Do I need to use something like ALAssetsLibrary for this?

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes, Use ALAssetsLibrary → now called PHAsset.

You should get the NSData of the gif, not UIImage( because UIImage will only get the first frame.)

So basically you would do something like this:

One you get the asset

let requestOptions = PHImageRequestOptions()
requestOptions.isSynchronous = true // adjust the parameters as you wish    

PHImageManager.default().requestImageData(for: asset, options: requestOptions, resultHandler: { (imageData, UTI, _, _) in
    if let uti = UTI,let data = imageData ,
        // you can also use UTI to make sure it's a gif
       UTTypeConformsTo(uti as CFString, kUTTypeGIF) {
        // save data here
    }
})      

Resource: PHAsset


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...