方法一:利用sqlite数据库的blob类型的数据存取
假定数据库中存在表 imageTable(name text,image blob), 下面代码将图片文件test.png的二进制数据写到sqlite数据库:
- NSString * filePath = [[NSBundle mainBundle] pathForResource: @"test" ofType:@"png"];
- if ([[NSFileManager defaultManager] fileExistsAtPath:filePath])//判断图片是否存在
- {
- char *name="test";
- NSData * imgData = UIImagePNGRepresentation([UIImage imageWithContentsOfFile:filePath]);
- const char * sequel = "insert into imageTable (name,image) values(?,?)";
- sqlite3_stmt * update;
- if (sqlite3_prepare_v2(database, sequel, -1, &update, NULL) == SQLITE_OK)
- {
- sqlite3_bind_text(update, 1, name, -1, NULL);
- sqlite3_bind_blob(update, 2, [imgData bytes], [imgData length], NULL);
- if( sqlite3_step(update) == SQLITE_DONE)
- {
- NSLog(@"已经写入数据");
- }
- sqlite3_finalize(update);
- }
- }
- else
- {
- NSLog(@"文件不存在");
- }
下面代码从数据库中读取图片二进制数据,然后显示图片:
- const char * sequel = "select image from imageTable where name=?";
- sqlite3_stmt * getimg;
- if (sqlite3_prepare_v2(database, sequel, -1, &getimg, NULL) == SQLITE_OK)
- {
- char *name = "test";
- sqlite3_bind_text(update, 1, name, -1, NULL);
- if(sqlite3_step(getimg) == SQLITE_ROW)
- {
- int bytes = sqlite3_column_bytes(getimg, 0);
- Byte * value = (Byte*)sqlite3_column_blob(getimg, 1);
- if (bytes !=0 && value != NULL)
- {
- NSData * data = [NSData dataWithBytes:value length:bytes];
- UIImage * img = [UIImage imageWithData:data];
- UIImageView * aview =[[UIImageView alloc] initWithFrame:CGRectMake(0.0, 0.0, IMAGE_WIDTH, IMAGE_HEIGHT)];
- aview.image = img;
- [self.view addSubview:aview];
- }
- }
- sqlite3_finalize(getimg);
- }
方法二:将图片转化成base64编码格式的字符串,直接以字符串的形式存放入数据库
存取方法不做过多介绍,上篇已经做过介绍,主要展示以下转化过程:
- //图片转化为base64字符串
- UIImage *originImage = [UIImage imageNamed:@"origin.png"];
- NSData *data = UIImageJPEGRepresentation(originImage, 1.0f);
- NSString *encodedImageStr = [data base64Encoding];
- NSLog(@"Encoded image:%@", encodedImageStr);
- //base64字符串转化为图片
- NSData *decodedImageData = [[NSData alloc] initWithBase64Encoding:encodedImageStr];
- UIImage *decodedImage = [UIImage imageWithData:decodedImageData];
- NSLog(@"Decoded image size: %@", NSStringFromCGSize(decodedImage.size));