如何将创建的gif保存到照片中? (目前仅适用于第一次)

问题描述 投票:0回答:1

在我的动画应用程序中,我想将动画另存为 gif 到照片应用程序。现在,我第一次成功将其保存到照片中的代码,但之后它生成一个错误(PHPhotosErrorDomain 错误 -1。)generateGifFromImages 函数似乎可以工作,因为我可以在目标文件夹中找到所有 gif 文件,但是(除了我第一次这样做)他们只是没有保存到照片。

我正在使用此代码从图像数组创建 gif:

import UIKit
import MobileCoreServices

public class GIFFromImages {
    public enum colorSpace {
        case rgb
        case gray
    }
    public init () {}
}

extension GIFFromImages {
    public func makeFileURL(filename: String) -> URL {
        let gifDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
        let gifFileURL = gifDirectory.appendingPathComponent(filename)
        return gifFileURL
    }
    
    public func generateGifFromImages(images: [UIImage], fileURL: URL, colorSpace: colorSpace, delayTime: Double, loopCount: Int) {
        let gifGroup = DispatchGroup()
        var tempImages: [UIImage] = []
        for image in images {
            gifGroup.enter()
            let imageWidth = UIScreen.main.bounds.width
            let imageHeight = UIScreen.main.bounds.height
            
            let imageRect: CGRect = CGRect(x:0, y:0, width: imageWidth, height: imageHeight)
            let imageBitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.none.rawValue)
            let context = CGContext(data: nil, width: Int(imageWidth), height: Int(imageHeight), bitsPerComponent: 8, bytesPerRow: 0, space: CGColorSpaceCreateDeviceGray(), bitmapInfo: imageBitmapInfo.rawValue)
            
            
            
            if let cgImg = image.cgImage {
                
                //Set bg as white
                context?.setFillColor(UIColor.white.cgColor)
                context?.fill(imageRect)
                
                context?.draw(cgImg, in: imageRect)
                if let makeImg = context?.makeImage() {
                    let imageRef = makeImg
                    let newImage = UIImage(cgImage: imageRef)
                    tempImages.append(newImage)
                    gifGroup.leave()
                }
            }
        }
        
        gifGroup.notify(queue: .main) {
            let gifFileProperties: CFDictionary = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFLoopCount as String: loopCount]]  as CFDictionary
            let gifFrameProperties: CFDictionary = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFDelayTime as String: delayTime]] as CFDictionary
            if let url = fileURL as CFURL? {
                if let destination = CGImageDestinationCreateWithURL(url, kUTTypeGIF, images.count, nil) {
                    CGImageDestinationSetProperties(destination, gifFileProperties)
                    for image in tempImages {
                        if let cgImage = image.cgImage {
                            CGImageDestinationAddImage(destination, cgImage, gifFrameProperties)
                        }
                    }
                    if !CGImageDestinationFinalize(destination) {
                        print("Failed to finalize the image destination")
                    }
                }
            }
        }
    }
}


我正在调用它并通过此按钮保存到照片:

Button {
                    
                    print("Saving animation titled: \(animation.title)")
                    
                    var images: [UIImage] = []
                    
                    for frame in animation.frames {
                        let image = try! PKDrawing(data: frame.frameData).generateThumbnail(scale: 1)
                        images.append(image)
                    }
                    
                    let timestamp = Date().timeIntervalSince1970
                    let timestampString = String(format: "%.0f", timestamp)
                    let gifURL = gifManager.makeFileURL(filename: "\(timestampString).gif")
                    
                    gifManager.generateGifFromImages(images: images, fileURL: gifURL, colorSpace: .rgb, delayTime: (1.0/Double(animation.framesPerSecond)), loopCount: 0)
                    
                    
                    // Save the generated GIF to the Photos library
                    PHPhotoLibrary.shared().performChanges({
                        
                        // Check if the GIF file exists
                        if FileManager.default.fileExists(atPath: gifURL.path) {
                            print("GIF file exists at:", gifURL.path)
                        } else {
                            print("Error: GIF file does not exist at:", gifURL.path)
                        }
                        
                        PHAssetChangeRequest.creationRequestForAssetFromImage(atFileURL: gifURL)
                    }) { success, error in
                        if success {
                            print("GIF saved successfully.")
                        } else {
                            print("Error saving GIF:", error?.localizedDescription ?? "Unknown error")
                        }
                    }
                    
                    close()
                    
                } label: {
                    
                    ZStack {
                        Rectangle()
                            .frame(width: 400, height: 100)
                            .foregroundColor(.accentColor)
                            .cornerRadius(30)
                        Text("Save GIF to Photos")
                            .foregroundStyle(.white)
                            .font(.title)
                            .bold()
                    } 
                }
swift file swiftui save phphotolibrary
1个回答
0
投票

我找到了一个解决方案——我在generateGifFromImages函数中添加了一个完成处理程序,然后按照这个答案替换我将gif保存到照片的代码:Save gif to iOS Photo Library in Swift

© www.soinside.com 2019 - 2024. All rights reserved.