Search code examples
iosswift

Storing and Retrieving Image in Sqlite with swift


How to store and fetch images in SQLite and in what format the images get saved? It would be more helpful if explained with an example.


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 SQLite DB. Remember to use text as column type because this string is very long.

    To decode back to UIImage:

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