从 UIImageView 将 GIF 图像保存在照片库中

Save GIF Image in Photo Gallery from UIImageView

我有显示 GIF 图片的 UIImageView,现在我无法将 GIF 图片保存到照片库中。

我正在使用下面的 swift 代码

guard let image = imageView.image else { return }

UIImageWriteToSavedPhotosAlbum(image,
self, 
#selector(savedImage), 
nil);

当我使用上面的代码时,它只在照片库中保存单张图像,而不是保存为 GIF。

需要建议,如何将从 URL 加载的或在 UIImageView 中可用的 GIF 保存到图库中。

首先你需要从imageView中获取gif的所有图像和图像的持续时间,现在你可以生成gif并保存在文档目录中。最后,将文件从URL保存到相册

 import ImageIO
 import Photos
 import MobileCoreServices

@IBAction func btnSaveGifFilePressed(_ sender: Any) {
    
    if let imgs = self.imgView.image?.images, imgs.count > 0 {
        var animationDuration = self.imgView.image?.duration ?? 1.0
        animationDuration = animationDuration / Double(imgs.count);
        
        let url = FileManager.default.urlForFile("lion.gif")
        FileManager.default.createGIF(with: imgs, url: url, frameDelay: animationDuration)
        
        PHPhotoLibrary.shared().performChanges ({
            PHAssetChangeRequest.creationRequestForAssetFromImage(atFileURL: url)
        }) { saved, error in
            if saved {
                print("Your image was successfully saved")
            }
        }
    }
}

使用以下代码创建 GIF。

func createGIF(with images: [UIImage], url: URL, frameDelay: Double) {

    if let destinationGIF = CGImageDestinationCreateWithURL(url as CFURL, kUTTypeGIF, images.count, nil) {
        let properties = [
            (kCGImagePropertyGIFDictionary as String): [(kCGImagePropertyGIFDelayTime as String): frameDelay]
        ]
        
        for img in images {
            let cgImage = img.cgImage
            CGImageDestinationAddImage(destinationGIF, cgImage!, properties as CFDictionary?)
        }
        CGImageDestinationFinalize(destinationGIF)
    }
}

在单行中得到一个URL:

func urlForFile(_ fileName: String, folderName: String? = nil) -> URL {
  
    var documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
    
    if let folder = folderName {
        documentsDirectory = documentsDirectory.appendingPathComponent(folder)
        if !self.fileExists(atPath: documentsDirectory.path) {
            try? self.createDirectory(atPath: documentsDirectory.path, withIntermediateDirectories: true, attributes: nil)
        }
    }
    
    let fileURL = documentsDirectory.appendingPathComponent(fileName)
    return fileURL;
}