Storing and Retrieving Image in Sqlite with swift

前端 未结 3 718
小蘑菇
小蘑菇 2020-12-21 20:05

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.

3条回答
  •  被撕碎了的回忆
    2020-12-21 20:25

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

提交回复
热议问题