Save NSImage with FMDB in Quick

I am working on CarRental apps for OS X in quick mode. I have an NSImageView where a user can delete an image and some text fields. Vehicle data is stored in an array of Car objects. I need to write this data to a SQLite database with FMDB. I have no problems with the text, but how to save the picture? The following code works without errors, but it does not save the image correctly.

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 image using FMDB?

0
source share
2 answers

FMDB can save NSData objects in SQLite as a BLOB. So, the only question is how to get the presentation of NSData (like PNG, JPEG, TIFF, etc.) Images.

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

If you only have an NSImage object, you can create a view for this image. This is usually not ideal, because you can often make your asset larger than it was originally, and / or you can introduce quality losses.

If you want to get a PNG representation of an image, you can 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 Rajiv points out, if your images are large (i.e., the size is not reduced), SQLite is poorly suited for storing blobs. Thus, you can save the digital asset in the file system (for example, in the sandbox of your application), and then save only the relative link to this file in the SQLite database.

0
source

Do not save the entire image in FMDB.

Save the image in the sandbox and just save the image path to FMDB.

Read more about saving images in the sandbox here

How to Save Image to Sandbox - iPhone SDK

+1
source

All Articles