Search code examples
iosswiftsqlitefmdb

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.


Solution

  • 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)!