前端之家收集整理的这篇文章主要介绍了
sqlite数据库插入和读取图片数据 (for ios),
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在iOS下用sqlite数据库存储图片,先把你的图片转换成 NSData 形式,然后在数据库添加一行 blob 数据
假定数据库中存在表 test_table(name,image),下面代码将图片文件test.png的二进制数据写到sqlite数据库:
02 |
NSString * nameString = [NSString stringWithCString:name encoding:NSUTF8StringEncoding]; |
03 |
NSString * filePath = [[NSBundle mainBundle] pathForResource:nameString ofType:@ "png" ]; |
04 |
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) |
06 |
NSData * imgData = UIImagePNGRepresentation([UIImage imageWithContentsOfFile:filePath]); |
07 |
const char * sequel = "insert into test_table(name,image) values(?,?)" ; |
09 |
sqlite3_stmt * update; |
10 |
if (sqlite3_prepare_v2(database,sequel,-1,&update,NULL) == sqlITE_OK) |
12 |
sqlite3_bind_text(update,1,name,NULL); |
13 |
sqlite3_bind_blob(update,2,[imgData bytes],[imgData length],NULL); |
14 |
if ( sqlite3_step(update) == sqlITE_DONE) |
18 |
sqlite3_finalize(update); |
27 |
const char * sequel = "select image from test_table where name=?" ; |
28 |
sqlite3_stmt * getimg; |
29 |
if (sqlite3_prepare_v2(database,&getimg,NULL) == sqlITE_OK) |
32 |
sqlite3_bind_text(update,NULL); |
33 |
if (sqlite3_step(getimg) == sqlITE_ROW) |
35 |
int bytes = sqlite3_column_bytes(getimg,0); |
36 |
Byte * value = (Byte*)sqlite3_column_blob(getimg,1); |
37 |
if (bytes !=0 && value != NULL) |
39 |
NSData * data = [NSData dataWithBytes:value length:bytes]; |
40 |
UIImage * img = [UIImage imageWithData:data]; |
41 |
UIImageView * aview =[[UIImageView alloc] initWithFrame: |
42 |
CGRectMake(0.0,0.0,IMAGE_WIDTH,IMAGE_HEIGHT)]; |
44 |
[self.view addSubview:aview]; |
48 |
sqlite3_finalize(getimg); |
原文链接:https://www.f2er.com/sqlite/200505.html