如何从照片库加载动画 GIF [英] How to load animated GIF from photo library
问题描述
在 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.
这是我目前所拥有的:
@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屋!