【问题标题】:Storing and retrieving image from sqlite database in iOS在 iOS 中从 sqlite 数据库中存储和检索图像
【发布时间】:2015-08-01 16:21:33
【问题描述】:
- (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);
}

上面是我的代码 sn-p。 图像被保存到SQLiteDataBase,但问题是在获取图像时,在输入图像视图时我没有得到任何价值。 我已经做了一段时间了。做了更多的研究,但无法解决。 如果有人可以解决这个问题,请建议我。

【问题讨论】:

    标签: ios objective-c sqlite


    【解决方案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];
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-16
      • 1970-01-01
      • 1970-01-01
      • 2011-12-30
      • 2011-09-24
      • 1970-01-01
      • 1970-01-01
      • 2011-03-21
      相关资源
      最近更新 更多