Storing and retrieving image from sqlite database in iOS

- (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);
}

      

Above is my code snippet. The image is saved in SQLiteDataBase

, but the problem is that when I fetch the image, I am not getting any value when presenting the feed to the image. I've been doing this for a while. Did more research but couldn't solve it. Please suggest me if anyone will resolve this.

+3


source to share


1 answer


You are trying to store a complete image in the database.

But if you store the image in the document directory path .

And this path is stored in the database.

It is then easy to store and retrieve the image.

Below is my code.



To save the image in the path to the document directory

 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
{
}

      

And to get the image

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

      

0


source







All Articles