快速在Sqlite中存储和检索图像 [英] Storing and Retrieving Image in Sqlite with swift
问题描述
如何在SQLite中存储和获取图像以及以何种格式保存图像?举个例子解释会更有用.
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.
推荐答案
图像本身无法存储到数据库列中,但您可以先将其转换为字符串,然后再存储.该字符串称为base64字符串.据我所知,任何图像都可以反向转换为该图像.
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.
要以64为底进行编码:
let image : UIImage = UIImage(named:"imageNameHere")!
let imageData:NSData = UIImagePNGRepresentation(image)!
let strBase64 = imageData.base64EncodedString(options: .lineLength64Characters)
现在,您的UIImage对象将转换为String!将strBase64保存到SQLite DB.请记住使用 text
作为列类型,因为此字符串很长.
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.
要解码回UIImage:
let dataDecoded:NSData = NSData(base64EncodedString: strBase64, options: NSDataBase64DecodingOptions(rawValue: 0))!
let decodedimage:UIImage = UIImage(data: dataDecoded)!
这篇关于快速在Sqlite中存储和检索图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!