我在DBBrowser中创建了一个图像文件,现在我想在其中保存图像然后检索它。 这是我的代码 -
-(void)saveListImages {
if(sqlite3_open([[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:image] UTF8String], &database) == SQLITE_OK) {
NSString *query = [NSString stringWithFormat:@"SELECT * FROM image where id=%i"];
//NSLog(@";query = \n%@";, query);
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(database, [query UTF8String], -1, &statement, nil) == SQLITE_OK) {
while (sqlite3_step(statement) == SQLITE_ROW) {
if (sqlite3_column_blob(statement, 0) != NULL) {
//NSLog(@";read a non NULL image");
NSData *data = [[NSData alloc] initWithBytes:sqlite3_column_blob(statement, 0) length:sqlite3_column_bytes(statement, 0)];
imageView.image = [UIImage imageWithData:data];
}
else {
NSLog(@";read a NULL image");
}
}
sqlite3_finalize(statement);
}
}
sqlite3_close(database);
}
答案 0 :(得分:1)
你不能将图像存储在数据库中, 首先将图像转换为NSString,并在数据库图像列中将类型设置为blob
- (NSString *)encodeToBase64String:(UIImage *)image {
return [UIImagePNGRepresentation(image) base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithCarriageReturn];
}
- (UIImage *)decodeBase64ToImage:(NSString *)strEncodeData {
NSData *data = [[NSData alloc]initWithBase64EncodedString:strEncodeData options:NSDataBase64DecodingIgnoreUnknownCharacters];
return [UIImage imageWithData:data];
}
将图像转换为Base64String
NSString *imageString = [self encodeToBase64String:image];
// Store base64String into Database
需要时在imageView中显示图像, 只需从数据库中获取图像字符串而不是转换为图像
imageView.image=[self decodeBase64ToImage:imageString];