我將圖像轉換爲數據並在數據庫中保存圖像如下 NSData * imageData = UIImagePNGRepresentation(imgView.image);如何保存並從Sqlite數據庫檢索圖像?
[dataArray addObject:imageData];
和檢索數據到相關圖片如下
NSData *imdata = [[tableArray objectAtIndex:indexPath.row] objectForKey:@"Image"];
SQlite的代碼保存:
if (sqlite3_open([databasePath UTF8String], &database)== SQLITE_OK)
{
NSString *statement;
sqlite3_stmt *compiledstatement;
int Id;
NSString *Name;
NSData *imgData;
Id = [[recordArray objectAtIndex:0] intValue];
Name = [recordArray objectAtIndex:1];
imgData = [recordArray objectAtIndex:2];
statement = [[NSString alloc]initWithFormat:@"insert into ImageTable values ('%d','%@','%@')",Id,Name,imgData] ;
const char *sqlstatement = [statement UTF8String];
if (sqlite3_prepare_v2(database, sqlstatement, -1, &compiledstatement, NULL)== SQLITE_OK) {
if (SQLITE_DONE!=sqlite3_step(compiledstatement)) {
NSAssert1(0,@"Error when inserting %s",sqlite3_errmsg(database));
}
else {
NSLog(@"Data inserted Successfully");
}
//[recordDict release];
}
else {
NSLog(@"Failed with error");
NSAssert1(0,@"Error when creation %s",sqlite3_errmsg(database));
}
}
//sqlite3_finalize(compiledstatement);
sqlite的代號爲獲得:
- (NSMutableArray *) getRecord
{
[self checkAndCreateDatabase];
sqlArray=[[NSMutableArray alloc]init ];
if (sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK)
{
const char *sql = "select * from ImageTable";
sqlite3_stmt *selectstmt;
if(sqlite3_prepare_v2(database, sql, -1, &selectstmt, NULL) == SQLITE_OK)
{
while(sqlite3_step(selectstmt) == SQLITE_ROW)
{
//[sqlDict retain];
sqlDict =[[NSMutableDictionary alloc]init ];
NSString *Id = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 0)];
//[barcodeArray addObject:prdbcode];
[sqlDict setObject:Id forKey:@"Id"];
//[prdbcode release];
NSString *name = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 1)];
//[nameArray addObject:prdname];
[sqlDict setObject:name forKey:@"Name"];
//[prdname release];
NSData *image = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 2)];
//NSData *data = [[NSData alloc] initWithBytes:sqlite3_column_blob(selectstmt, 1) length:sqlite3_column_bytes(selectstmt, 1)];
//[descArray addObject:prdDesc];
[sqlDict setObject:image forKey:@"Image"];
// [prdDesc release];
[sqlArray addObject:sqlDict];
}
sqlite3_finalize(selectstmt);
}
sqlite3_close(database);
//
}
return sqlArray;
}
[imView setImage:[UIImage imageWithData:imdata]];
[cell addSubview:imView];
Id和Name被檢索但圖像沒有顯示。 應用程序終止,沒有任何錯誤消息。 請讓我知道這個解決方案
這與SQLite有什麼關係? –
類似的問題: http://stackoverflow.com/questions/10192945/to-reterive-blob-image-from-sqlite 希望你得到你的問題就解決了。 – anjum