save NSImage with FMDB in swift

只谈情不闲聊 提交于 2019-12-25 03:32:36

问题


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?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/30696527/save-nsimage-with-fmdb-in-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!