save NSImage with FMDB in swift

1k views Asked by At

I'm working on a CarRental App for OS X in swift. I have a NSImageView where the user can drop a picture and some TextFields. The car data are stored in an array of Car Objects. I need to write this data to an SQLite database with FMDB. I have no problems with the text, but how to save the picture? The below code runs without error but it does not save the image correctely.

let sql = "INSERT INTO tblCars (cMakeModel, cPrice, cPhoto) VALUES (?,?,?)"

    if let db = DBManager.openDB(dbName) {

        for var i = 0; i < carsArray.arrangedObjects.count; ++i {
            let car = carsArray.arrangedObjects[i] as CarData

            let ok = db.executeUpdate(sql, withArgumentsInArray: [car.makeModel, car.price, car.photo!])

            if !ok {
                println("Error: \(db.lastErrorMessage())")
                return
            }
        }
        println("Car added")
    }

How to save an Image with FMDB?

2

There are 2 answers

0
Rob On BEST ANSWER

FMDB can save NSData objects in SQLite as BLOBs. So, the only question is how to get NSData representation (e.g. PNG, JPEG, TIFF, etc.) of the image.

If possible, one should use the original digital asset you used to create the NSImage in the first place. For example, if you loaded it from a PNG or JPEG file, go back and get the NSData from that file.

If you only have a NSImage object, you can create a representation for that image. This generally not ideal because you often can make the asset bigger than it was originally and/or you can introduce quality loss.

If you wanted to get a PNG representation of the image, though, you could do something like:

func PNGRepresentation(image: NSImage) -> NSData? {
    if let TIFFRepresentation = image.TIFFRepresentation, bitmap = NSBitmapImageRep(data: TIFFRepresentation) {
        return bitmap.representationUsingType(.NSPNGFileType, properties: [:])
    }

    return nil
}

As Rajeev points out, if your images are large (i.e. not thumbnail sized) SQLite is poorly suited for storing large binary objects. So you might store the digital asset in the file system (e.g. in your app's sandbox) and then only store a relative reference to that file in the SQLite database.

0
Rajeev Bhatia On

Do not save the entire image in the FMDB.

Save the image in the sandbox and simply save the image path in FMDB.

More info on saving the image in sandbox here

How do I save an image to the sandbox - iPhone SDK