小编典典

快速在Sqlite中存储和检索图像

swift

如何在SQLite中存储和获取图像以及以什么格式保存图像?如果用一个例子来解释会更有用。


阅读 285

收藏
2020-07-07

共1个答案

小编典典

图像本身无法存储到数据库列中,但是您可以先将其转换为字符串,然后再存储。该字符串称为base64字符串。据我所知,任何图像都可以转换为相反的图像。

编码为基数64:

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

现在,您的UIImage对象将转换为String!将strBase64保存到SQLite DB。记住要text用作列类型,因为此字符串很长。

解码回UIImage:

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