我需要找到这种方法的替代方法来保存图像

let save = UserDefaults.standard
let imageData = UIImageJPEGRepresentation(Photo.image!, 1.0)
save.set(imageData, forKey: "Image")
save.synchronize()
if let imgData = save.object(forKey: "Image"){
     let compressedJPGImage = UIImage(data: imgData as! Data)
}

并加载图像
let imgData = save.object(forKey: "Image")
let compressedJPGImage = UIImage(data: imgData as! Data)
Photo.image = compressedJPGImage

这种方法的问题在于,我用UserDefaults.standard保存了很多其他值,因此在同步时需要花费很多时间(5-10分钟)。

最佳答案

不建议将大文件(如图像)保存到UserDefaults。 UserDefaults旨在保存很小的数据,例如用户喜欢的应用程序主题颜色。也许合适的选择是将图像保存在文档目录中。这是一个允许您保存图像的功能:

    func saveImage(image: UIImage) -> String {

    let imageData = NSData(data: UIImagePNGRepresentation(image)!)
    let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory,  FileManager.SearchPathDomainMask.userDomainMask, true)
    let docs = paths[0] as NSString
    let uuid = NSUUID().uuidString + ".png"
    let fullPath = docs.appendingPathComponent(uuid)
    _ = imageData.write(toFile: fullPath, atomically: true)
   return uuid

   }

上面的功能将为您创建保存图像的名称。如果您希望指定要保存的图像的名称,则可以执行以下操作(但是您将负责确保指定的图像名称是唯一的):
    func saveImage(image: UIImage, withName name: String) {

     let imageData = NSData(data: UIImagePNGRepresentation(image)!)
     let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory,  FileManager.SearchPathDomainMask.userDomainMask, true)
     let docs = paths[0] as NSString
     let name = name
     let fullPath = docs.appendingPathComponent(name)
     _ = imageData.write(toFile: fullPath, atomically: true)
     }

要检索这些图像,可以将图像名称传递给此函数:
     func getImage(imageName: String) -> UIImage? {

     var savedImage: UIImage?

     if let imagePath = getFilePath(fileName: imageName) {
     savedImage = UIImage(contentsOfFile: imagePath)
     }
     else {
    savedImage = nil
     }

    return savedImage

    }

依靠此功能来工作:
    func getFilePath(fileName: String) -> String? {

    let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
    let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
    var filePath: String?
    let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
    if paths.count > 0 {
    let dirPath = paths[0] as NSString
    filePath = dirPath.appendingPathComponent(fileName)
    }
   else {
    filePath = nil
   }

   return filePath
   }

这是一个如何保存图像而不是UserDefaults的示例。我正在保存图片,我将其称为“图片”:
    saveImage(image: Photo.image, withName name: "Image")

这是我将如何检索保存的图像的示例:
    if let theSavedImage = getImage(imageName: "Image") {
        //I got the image
    }

关于ios - Swift 3-另存图片,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44640081/

10-09 09:51