加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-12 20:01:39 所属栏目:百科 来源:网络整理
导读:在iOS下用sqlite数据库存储图片,先把你的图片转换成 NSData 形式,然后在数据库添加一行 blob 数据 假定数据库中存在表 test_table(name,image),下面代码将图片文件test.png的二进制数据写到sqlite数据库: 01 char *name = "test" ; 02 NSString * nameStr
01char*name = "test";02NSString * nameString = [NSString stringWithCString:name encoding:NSUTF8StringEncoding];03NSString * filePath = [[NSBundle mainBundle] pathForResource:nameString ofType:@"png"];04if([[NSFileManager defaultManager] fileExistsAtPath:filePath])05{06NSData * imgData = UIImagePNGRepresentation([UIImage imageWithContentsOfFile:filePath]);07constchar* sequel = "insert into test_table(name,image) values(?,?)";0809sqlite3_stmt * update;10if(sqlite3_prepare_v2(database,sequel,-1,&update,NULL) == SQLITE_OK)11{12sqlite3_bind_text(update,1,name,NULL);13sqlite3_bind_blob(update,2,[imgData bytes],[imgData length],NULL);14if( sqlite3_step(update) == SQLITE_DONE)15{16NSLog(@"已经写入数据");17}18sqlite3_finalize(update);19} 20}21else22{23NSLog(@"文件不存在");24}2526下面代码从数据库中读取图片二进制数据,然后显示图片:27const char* sequel = "select image from test_table where name=?";28sqlite3_stmt * getimg;29if(sqlite3_prepare_v2(database,&getimg,NULL) == SQLITE_OK)30{31char*name = "test";32sqlite3_bind_text(update,NULL);33if(sqlite3_step(getimg) == SQLITE_ROW)34{35intbytes = sqlite3_column_bytes(getimg,0);36Byte * value = (Byte*)sqlite3_column_blob(getimg,1);37if(bytes !=0 && value != NULL)38{39NSData * data = [NSData dataWithBytes:value length:bytes];40UIImage * img = [UIImage imageWithData:data];41UIImageView * aview =[[UIImageView alloc] initWithFrame:42CGRectMake(0.0,0.0,IMAGE_WIDTH,IMAGE_HEIGHT)];43aview.image = img;44[self.view addSubview:aview];45[aview release];46}47}48sqlite3_finalize(getimg);49}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

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

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

    推荐文章
      热点阅读