在iOS中從sqlite數據庫存儲和檢索圖像



objective-c sqlite3 (1)

您嘗試在數據庫中存儲完整的圖像。

但是,如果您將圖像存儲在文檔目錄路徑中

而這個路徑存儲到數據庫。

然後很容易存儲和檢索圖像。

以下是我的代碼。

用於在文檔目錄路徑中保存圖像

 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];
}

https://src-bin.com

- (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但問題是,在獲取圖像時,我沒有得到任何價值時飼料圖像視圖。 我已經做了一段時間了。 做了更多的研究,但解決不了。 如果有人能解決這個問題,請告訴我。





sqlite3