Kevtho
Kevtho

Reputation: 203

Save image in Blob field FMDB

I've read lot of tutorials but I can't save an image into a sql table. I'm using the FMDB framework to connect my swift app and the sqlite database. This is the database

CREATE TABLE "PRODUCTO" (
    `CODIGOPRODUCTO`    integer NOT NULL PRIMARY KEY AUTOINCREMENT,
    `CODIGOCATEGORIA`   integer NOT NULL,
    `NOMBREPRODUCTO`    varchar(50) NOT NULL,
    `DESCRIPCIONPRODUCTO`   varchar(50) NOT NULL,
    `IMAGEN`    BLOB,
    FOREIGN KEY(`CODIGOCATEGORIA`) REFERENCES `CATEGORIA`(`CODIGOCATEGORIA`)
) 

this is the way to create and save the object

let newPr: Producto = Producto()
newPr.nombre = txtNombre.text!
newPr.descripcion = txtDescripcion.text!
newPr.idCategoria = Int(categoriaSel.id)
newPr.imagen = imageView.image!
Producto().insertar(itemProducto: newPr)

Finally this is sql sentence used in the function "insertar"

conexion.database!.open()
        let consulta: Bool = conexion.database!.executeUpdate("insert into PRODUCTO (CODIGOCATEGORIA,NOMBREPRODUCTO,DESCRIPCIONPRODUCTO, IMAGEN) values (\(itemProducto.idCategoria),'\(itemProducto.nombre)','\(itemProducto.descripcion)', \(UIImagePNGRepresentation(itemProducto.imagen)! as NSData))", withArgumentsIn: nil)
        conexion.database!.close()

But this code always fails.

Upvotes: 2

Views: 1594

Answers (2)

Fangming
Fangming

Reputation: 25260

Image itself cannot be stored into a database columns but you can first convert it into a string and then store it. The string is called base64 string. As far as I know, any image can be converted to that and reversely.

To encode to base 64:

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

Now your UIImage object is converted to a String! Save strBase64 to your DB. Remember to use text as column type because this string is very long. BLOB should also work!

To decode back to UIImage:

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

Upvotes: -4

Rob
Rob

Reputation: 438037

When inserting blobs, you cannot use string interpolation to build the SQL. (In fact, you really shouldn't do that to insert values in SQL statements, anyway.) You should use ? placeholders in your SQL and then pass the values in as a parameter of executeUpdate:

do {
    try conexion.database!.executeUpdate("insert into PRODUCTO (CODIGOCATEGORIA,NOMBREPRODUCTO,DESCRIPCIONPRODUCTO, IMAGEN) values (?, ?, ?, ?)", values: [itemProducto.idCategoria, itemProducto.nombre, itemProducto.descripcion, UIImagePNGRepresentation(itemProducto.imagen)!])
} catch {
    print(error)
}

Upvotes: 5

Related Questions