使用swift在Sqlite中存储和检索图像

时间:2017-06-27 12:59:31

标签: ios swift

如何在SQLite中存储和获取图像以及图像保存的格式?如果用一个例子来解释会更有帮助。

3 个答案:

答案 0 :(得分:8)

图像本身不能存储到数据库列中,但您可以先将其转换为字符串然后存储它。该字符串称为base64字符串。据我所知,任何图像都可以转换为相反的图像。

要编码到base 64:

let image : UIImage = UIImage(named:"imageNameHere")!
let imageData:NSData = UIImagePNGRepresentation(image)!
let strBase64 = imageData.base64EncodedString(options: .lineLength64Characters)

现在你的UIImage对象被转换为String!将strBase64保存到SQLite DB。请记住使用text作为列类型,因为此字符串非常长。

要解码回UIImage:

let dataDecoded:NSData = NSData(base64EncodedString: strBase64, options: NSDataBase64DecodingOptions(rawValue: 0))!
let decodedimage:UIImage = UIImage(data: dataDecoded)!

答案 1 :(得分:1)

<强>替代

  1. 将图像保存到文档目录中。
  2. 在sqlite中保存图像文件路径或图像名称
  3. 从sqlite获取图像路径或名称,并从文档目录访问该路径。
  4. 参考:Iphone : How to Display Document Directory images in Image View?

答案 2 :(得分:1)

您也可以将图像直接存储为BLOB,但这取决于您用于SQLite访问的框架。如果您使用SQLite.swift,则有一个选项:

像这样设置文件SQLiteHelper.swift

class SQLiteHelper{
    var db: Connection!

    let personsTable = Table("person")
    let id = Expression<Int>("id")
    let firstName = Expression<String>("firstName")
    let lastName = Expression<String>("lastName")
    let profileImage = Expression<Data>("profileImage")
    let date = Expression<Date>("savedAt")

    init() {
        do{
            let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
            let dbTemp = try Connection("\(path)/myDb.sqlite3") //Create db if not existing
            self.db = dbTemp
        }
        catch {
            print("Error info: \(error)")
        }
    }

    public func insertData(firstNameVal: String,
                           lastNameVal: String,
                           profileImageVal: Data,
                           dateVal: Date){

        do{
            //Create a new table only if it does not exist yet
            try db.run(personsTable.create(ifNotExists: true) { t in      // CREATE TABLE "person" (
                t.column(id, primaryKey: true)          //     "id" INTEGER PRIMARY KEY NOT NULL,
                t.column(firstName)                     //     "firstName" TEXT,
                t.column(lastName)                      //     "lastName" TEXT,
                t.column(profileImage)                  //     "profileImage" BLOB,
                t.column(date)                          //     "savedAt" DATETIME)
            })
        }
        catch {
            print("The new SQLite3 Table could not be added: \(error)")
        }

        do{
            try db.run(personsTable.insert(firstName <- firstNameVal,
                                            lastName <- lastNameVal,
                                            profileImage <- profileImageVal,
                                            date <- dateVal
            ))
        }
        catch {
            print("Could not insert row: \(error)")
        }
    }

    public func getData() -> [Person]{
        var persons = [Person]()
        do{
            for row in try db.prepare(personsTable) {
                let person: Person = Person(firstName: row[firstName],
                                               lastName: row[lastName],
                                               profileImage: row[profileImage],
                                               savedAt: row[date])

                persons.append(person)
            }
        }
        catch {
            print("Could not get row: \(error)")
        }
        return persons
    }

现在创建一个文件Person.swift并将以下结构放入其中:

import Foundation

struct Person: Identifiable {
    var id = UUID()
    var firstName: String
    var lastName: String
    var profileImage: Data
    var savedAt: Date
}

存储数据

为了将数据存储为.png BLOB ,现在基本上可以执行以下操作:

var databaseHelper: SQLiteHelper = SQLiteHelper.init()
self.databaseHelper.insertData(firstNameVal: "yourFirstName",
                                   lastNameVal: "yourLastName",
                              profileImageVal: yourImageView.pngData(),
                              dateVal: Date())

检索数据

如果以后要在另一个Imageview中显示图像,则必须执行以下操作:

var persons = self.databaseHelper.getData()
let profileImage = UIImage(data: persons[0].profileImage)
let myImageView = UIImageView(image: profileImage)

将UIImage保存为BLOB

我将图像另存为.png,因为我想在iOS之外使用数据库,因此希望确保兼容性。如果需要,还可以直接存储 UIImage 。您大概需要这样更改它:

let profileImage = Expression<UIImage>("profileImage")
...
profileImageVal: yourImageView,
...
let myImageView = persons[0].profileImage
...

import Foundation
import UIKit

struct Person: Identifiable {
    var id = UUID()
    var firstName: String
    var lastName: String
    var profileImage: UIImage
    var savedAt: Date
}

注意:SQLite.swift还支持延迟加载,在这种情况下这可能更有意义...