使用 swift 在应用程序中存储 UIImages 的正确方法是什么?

what's the correct way to store UIImages taken in app using swift?

我想允许用户拍照并将这张照片附加到将存储在 CoreData 中的“人”的个人资料中。

存储此 UIImage 的典型方式是什么?

已编辑

总的来说,每个 table("Person") 将包含一些字符串和这个 UIImage。

我不希望 UIImages 占用太多空间 space,所以当用户拍照时,我会在不影响视觉完整性的情况下将其裁剪并尽可能小地保存。不过这是另一种方法,以后再想办法。

知道这些 UIImage 的大小范围吗?我只需要每个个人资料的头像照片。就像 iPhone 上的“联系人”应用一样,我也希望能够通过 iMessage 或电子邮件与其他人分享这个“人”。

所以关于是否需要整个“人”文件的任何建议

100kb store in the same table as the relevant data

1mb store in a separate table attached via a relationship to avoid loading unnecessarily

1mb store on disk and reference it inside of Core Data

这里的代码可以帮助您将 UIImage 存储在 document directory 中,然后将 document path 存储到您的数据库中。

let nsDocumentDirectory = NSSearchPathDirectory.DocumentDirectory
let nsUserDomainMask = NSSearchPathDomainMask.UserDomainMask
if let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true) {
    if paths.count > 0 {
        if let dirPath = paths[0] as? String {

            let writePath = dirPath.stringByAppendingPathComponent("Image2.png") 
            UIImagePNGRepresentation(image).writeToFile(writePath, atomically: true)
        }
    }
}

希望对您有所帮助。

您可以在您的 Core Data 模型中使用 Transformable 类型 – 这样您就可以存储任何符合 NSCoding 的对象,其中包括 UIImage。您的图片将有效地保存在数据库中,这对您的应用来说可能更方便。

为了提高性能,还有一个允许外部存储的设置。小文件,只会以二进制形式存储在数据库中;较大的文件,将写入外部文件。这样做的好处是对您来说是透明的。

查看此问题了解更多详情:Storing UIImage in Core Data with the new External Storage flag