在iOS中从sqlite数据库存储和检索图像
- (void)viewDidLoad { [super viewDidLoad]; [self createDB]; } -(void)createDB { NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *docdir = [path objectAtIndex:0]; //path[0]; dbpath = [docdir stringByAppendingPathComponent:@"arun.sqlite"]; NSLog(@"database path : %@",dbpath); NSFileManager *filemgr = [NSFileManager defaultManager]; if ([filemgr fileExistsAtPath:dbpath] == NO) { //OPEN AND CREATE DATABASE if (sqlite3_open([dbpath UTF8String], &myDB) == SQLITE_OK) { //CREATE TABLE NSString *createSQL = @"CREATE TABLE IF NOT EXISTS STUDENT (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, ADDRESS TEXT, ROLLNO INTEGER,IMAGE BLOB)"; char *error = nil; if (sqlite3_exec(myDB, [createSQL UTF8String] , NULL, NULL, &error) == SQLITE_OK) { NSLog(@"Database and tables created."); } else { NSLog(@"Error %s",error); } sqlite3_close(myDB); } } } - (void)saveImage { sqlite3_stmt *compiledStmt; sqlite3 *db; if(sqlite3_open([dbpath UTF8String], &db)==SQLITE_OK) { NSString *insertSQL = [NSString stringWithFormat:@"INSERT INTO STUDENT (ROLLNO,IMAGE) VALUES(\"%@\", \"%@\")", rollnoTxt.text, selectImgvw.image]; if(sqlite3_prepare_v2(db,[insertSQL cStringUsingEncoding:NSUTF8StringEncoding], -1, &compiledStmt, NULL) == SQLITE_OK){ UIImage *image = selectImgvw.image; NSData *imgdata = UIImagePNGRepresentation(image); sqlite3_bind_blob(compiledStmt, 1, [imgdata bytes], (int)[imgdata length], SQLITE_TRANSIENT); if(sqlite3_step(compiledStmt) != SQLITE_DONE ) { NSLog( @"Error: %s", sqlite3_errmsg(db) ); } else { NSLog( @"Insert into row id = %lld", (sqlite3_last_insert_rowid(db))); } sqlite3_finalize(compiledStmt); } } sqlite3_close(db); } - (void)showImage { sqlite3_stmt *compiledStmt; sqlite3 *db; if(sqlite3_open([dbpath UTF8String], &db)==SQLITE_OK){ NSString *insertSQL = [NSString stringWithFormat:@"SELECT IMAGE FROM STUDENT WHERE ROLLNO = %@",rollnoTxt.text]; if(sqlite3_prepare_v2(db,[insertSQL cStringUsingEncoding:NSUTF8StringEncoding], -1, &compiledStmt, NULL) == SQLITE_OK) { while(sqlite3_step(compiledStmt) == SQLITE_ROW) { int length = sqlite3_column_bytes(compiledStmt, 0); NSData *imgdata = [NSData dataWithBytes:sqlite3_column_blob(compiledStmt, 0) length:length]; NSLog(@"Length : %ld", [imgdata length]); if(imgdata == nil) NSLog(@"No image found."); else { UIImage *img = [UIImage imageWithData:imgdata]; displayImgvw.image = img; } } } sqlite3_finalize(compiledStmt); } sqlite3_close(db); }
以上是我的代码片段。 图像被保存到SQLiteDataBase
但问题是,在获取图像时,我没有得到任何价值时饲料图像视图。 我已经做了一段时间了。 做了更多的研究,但解决不了。 如果有人能解决这个问题,请告诉我。
您尝试在数据库中存储完整的图像。
但是,如果您将图像存储在文档目录path中 。
而这个path存储到数据库。
然后很容易存储和检索图像。
以下是我的代码。
用于在文档目录path中保存图像
NSString *pathsToReources = [[NSBundle mainBundle] resourcePath]; NSString *yourOriginalDatabasePath = [pathsToReources stringByAppendingPathComponent:@"Demo.sqlite"]; NSArray *pathsToDocuments =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [pathsToDocuments objectAtIndex: 0]; NSString *dbPath = [documentsDirectory stringByAppendingPathComponent:@"Demo.sqlite"]; if (![[NSFileManager defaultManager] isReadableFileAtPath: dbPath]) { if ([[NSFileManager defaultManager] copyItemAtPath: yourOriginalDatabasePath toPath: dbPath error: NULL] != YES) NSAssert2(0, @"Fail to copy database from %@ to %@", yourOriginalDatabasePath, dbPath); } databasePath = [[NSString alloc]initWithString: [NSString stringWithFormat:@"%@",dbPath]]; const char *dbpath = [databasePath UTF8String]; sqlite3_stmt *statement; NSString * timestamp = [NSString stringWithFormat:@"%f.png",[[NSDate date] timeIntervalSince1970] * 1000]; NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES); NSString *documentsPath = [paths objectAtIndex:0]; NSString *smallpath=[NSString stringWithFormat:@"%@/%@",documentsPath,timestamp]; if(sqlite3_open(dbpath, &contactDB)==SQLITE_OK) { NSString *insertSQL = [NSString stringWithFormat:@"insert into Test values('%@','%@')",txtname.text,smallpath]; //img UIImage *img11=img1.image; NSData *data = (UIImageJPEGRepresentation(img11,1.0)); [data writeToFile:smallpath atomically:YES]; const char *inser_stmt=[insertSQL UTF8String]; sqlite3_prepare_v2(contactDB, inser_stmt, -1, &statement, NULL); if (sqlite3_step(statement) == SQLITE_DONE) { NSLog(@"Company Detail insert succesfully"); } else { //self.status.text = @"Failed to add contact"; } sqlite3_finalize(statement); sqlite3_close(contactDB); } else { }
并为检索图像
NSString *pathsToReources = [[NSBundle mainBundle] resourcePath]; NSString *yourOriginalDatabasePath = [pathsToReources stringByAppendingPathComponent:@"Demo.sqlite"]; NSArray *pathsToDocuments = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [pathsToDocuments objectAtIndex: 0]; NSString *dbPath = [documentsDirectory stringByAppendingPathComponent:@"Demo.sqlite"]; if (![[NSFileManager defaultManager] isReadableFileAtPath: dbPath]) { if ([[NSFileManager defaultManager] copyItemAtPath: yourOriginalDatabasePath toPath: dbPath error: NULL] != YES) NSAssert2(0, @"Fail to copy database from %@ to %@", yourOriginalDatabasePath, dbPath); } databasePath = [[NSString alloc]initWithString: [NSString stringWithFormat:@"%@",dbPath]]; const char *dbpath = [databasePath UTF8String]; sqlite3_stmt *statement; if (sqlite3_open(dbpath, &_database) == SQLITE_OK) { NSString *querySQL = [NSString stringWithFormat: @"SELECT Name,image FROM Test"]; const char *query_stmt = [querySQL UTF8String]; if (sqlite3_prepare_v2(_database, query_stmt, -1, &statement, NULL) == SQLITE_OK) { arrimage = [[NSMutableArray alloc] init]; arrname = [[NSMutableArray alloc] init]; while (sqlite3_step(statement) == SQLITE_ROW) { [arrname addObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement,0)]]; [arrimage addObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement,1)]]; } sqlite3_finalize(statement); } sqlite3_close(_database); [tblobj reloadData]; }