sqlite数据库插入和读取图片数据 (for ios)

在iOS下用sqlite数据库存储图片,先把你的图片转换成 NSData 形式,然后在数据库添加一行 blob 数据

假定数据库中存在表 test_table(name,image), 下面代码将图片文件test.png的二进制数据写到sqlite数据库:

01char *name = "test";
02NSString * nameString = [NSString stringWithCString:name encoding:NSUTF8StringEncoding];
03NSString * filePath = [[NSBundle mainBundle] pathForResource:nameString ofType:@"png"];
04if ([[NSFileManager defaultManager] fileExistsAtPath:filePath])
05{
06    NSData * imgData = UIImagePNGRepresentation([UIImage imageWithContentsOfFile:filePath]);
07    const  char * sequel = "insert into test_table(name,image) values(?,?)";
08  
09    sqlite3_stmt * update;
10    if (sqlite3_prepare_v2(database, sequel, -1, &update, NULL) == SQLITE_OK)
11    {
12        sqlite3_bind_text(update, 1, name, -1, NULL);
13        sqlite3_bind_blob(update, 2, [imgData bytes], [imgData length], NULL);
14        if( sqlite3_step(update) == SQLITE_DONE)
15        {
16           NSLog(@"已经写入数据");
17        }
18        sqlite3_finalize(update);
19    
20}
21else
22{
23    NSLog(@"文件不存在");
24}
25 
26下面代码从数据库中读取图片二进制数据,然后显示图片:
27const char * sequel = "select image from test_table where name=?";
28sqlite3_stmt * getimg;
29if (sqlite3_prepare_v2(database, sequel, -1, &getimg, NULL) == SQLITE_OK)
30{
31    char *name = "test";
32    sqlite3_bind_text(update, 1, name, -1, NULL);
33    if(sqlite3_step(getimg)  == SQLITE_ROW)
34    {
35        int bytes = sqlite3_column_bytes(getimg, 0);
36        Byte * value = (Byte*)sqlite3_column_blob(getimg, 1);
37        if (bytes !=0 && value != NULL)
38        {
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)];
43            aview.image = img;
44            [self.view addSubview:aview];
45            [aview release];
46         }
47     }
48     sqlite3_finalize(getimg);
49}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值