如何从照片库加载动画GIF [英] How to load animated GIF from photo library

查看:122
本文介绍了如何从照片库加载动画GIF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在iOS Swift中,我很难将动画GIF从设备照片库加载到UIImageView或从中创建.gif文件。如果它是服务器上的文件或者它在应用程序中是正确的,我可以显示动画GIF。但是,当我从照片库加载它时,我丢失了动画。我发现了一些Objective-C解决方案并尝试将它们转换为Swift,但没有任何运气。

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)

}

最好,我想将照片库图像保存到服务器上的gif文件中。从那里我可以毫不费力地显示它。但是,我需要一些帮助将照片库中的数据转换为某种类型的属性,而不会丢失动画。我是否需要使用像ALAssetsLibrary这样的东西?

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?

谢谢。

推荐答案

是的,使用ALAssetsLibrary→现在称为PHAsset。

Yes, Use ALAssetsLibrary → now called PHAsset.

你应该得到gif的NSData,而不是UIImage(因为UIImage只能得到第一帧。)

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:

你获得资产

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

资源: PHAsset

这篇关于如何从照片库加载动画GIF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆