【问题标题】:Save GIF Image in Photo Gallery from UIImageView从 UIImageView 将 GIF 图像保存在照片库中
【发布时间】:2020-11-28 20:27:30
【问题描述】:

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

我正在使用下面的快速代码

guard let image = imageView.image else { return }

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

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

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

【问题讨论】:

    标签: swift uiimageview uiimage gif


    【解决方案1】:

    首先你需要从 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)
        }
    }
    

    获取单行网址:

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

    【讨论】:

    • import ImageIO import Photos import MobileCoreServices 后我能够编译并执行任务
    猜你喜欢
    • 2011-05-11
    • 2017-10-11
    • 1970-01-01
    • 2013-12-11
    • 1970-01-01
    • 1970-01-01
    • 2015-10-20
    • 2015-06-19
    • 2014-03-01
    相关资源
    最近更新 更多