如何使用sqlite将图像保存到数据库中?

时间:2019-02-10 15:03:40

标签: swift database xcode sqlite

我正在制作一个应用程序,您可以在其中发布图像并将其显示在另一页上。我想将其保存到数据库中,但我不知道执行此操作的最佳方法。

3 个答案:

答案 0 :(得分:1)

您可以使用

将图像保存在文档文件夹中
func saveImage(image: UIImage) -> Bool {
    guard let data = UIImageJPEGRepresentation(image, 1) ?? UIImagePNGRepresentation(image) else {
        return false
    }
    guard let directory = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) as NSURL else {
        return false
    }
    do {
        try data.write(to: directory.appendingPathComponent("fileName.png")!)
        return true
    } catch {   
        print(error.localizedDescription)
        return false
    }
}

,您可以使用以下方法获取它的图像:

func getSavedImage(named: String) -> UIImage? {
    if let dir = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) {
        return UIImage(contentsOfFile: URL(fileURLWithPath: dir.absoluteString).appendingPathComponent(named).path)
    }
    return nil
}

答案 1 :(得分:0)

您可以快速使用核心数据保存图像核心数据是Apple在macOS和iOS操作系统中提供的对象图和持久性框架。 通过使用Core数据,您可以轻松访问sqlite数据库。

使用核心数据在Sqlite中保存图像 请参见 saving-picked-image-to-coredata

答案 2 :(得分:0)

您将图像保存在设备中,并将该图像的路径保存在Sqlite中。

此链接有关如何在设备Saving image and then loading it in Swift (iOS)中保存图像