Image not store in sqlite

后端 未结 2 774
甜味超标
甜味超标 2021-01-27 02:08

I made one demo which stores an Image to the database. Currently I am not getting any error but my image is not store in sqlite database. Please see the below code and tell me w

相关标签:
2条回答
  • 2021-01-27 02:19

    just replace this function to my code because you got wrong database path

    - (void) SaveImagesToSql: (NSData*) imgData  {
    
        directoryPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        documentsDirectory = [directoryPaths objectAtIndex:0];
        NSString * databasePath = [[NSString alloc]initWithString:[documentsDirectory stringByAppendingPathComponent:@"informationdb.sql"]];
    
        const char* sqlite3Query = "INSERT INTO PICTURES (PHOTO) VALUES (?)";
        int openDatabaseResult = sqlite3_open_v2([databasePath UTF8String], &sqlite3DatabaseObject, SQLITE_OPEN_READWRITE , NULL);
        if (openDatabaseResult == SQLITE_OK) {
            int sqlite3Prepare = sqlite3_prepare_v2(sqlite3DatabaseObject, sqlite3Query, -1, &sqlite3Statement, NULL);
            if( sqlite3Prepare == SQLITE_OK ) {
                sqlite3_bind_blob(sqlite3Statement, 1, [imgData bytes], [imgData length], SQLITE_TRANSIENT);
                sqlite3_step(sqlite3Statement);
            }
            else
            {
                NSLog(@"Error is: %s", sqlite3_errmsg(sqlite3DatabaseObject));
            }
            sqlite3_finalize(sqlite3Statement);
    
        }
        else NSLog( @"Error is:  %s", sqlite3_errmsg(sqlite3DatabaseObject) );
        sqlite3_close(sqlite3DatabaseObject);
    }
    

    here this is database screenshot

    Don't drag to database in your project.if any problem than tell me

    0 讨论(0)
  • 2021-01-27 02:29

    Here How I do modify as per your use.

    NSData *imageData = UIImagePNGRepresentation(imgView.image);
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    
    NSString *documentsDirectory = [paths objectAtIndex:0];
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setTimeStyle: NSDateFormatterShortStyle];
    dateFormatter.dateFormat = @"ddMMyyyyhhmmss_SSS_a";
    NSString *currentTime = [dateFormatter stringFromDate: [NSDate date]];
    
    NSString *imageName=[NSString stringWithFormat:@"Image_%@",currentTime];
    
    NSString *saveFilePath =[NSString stringWithFormat:@"%@.%@",imageName,@"png"];  //Store saveFilePath string to your database
    
    NSString *localFilePath1 = [documentsDirectory stringByAppendingPathComponent:saveFilePath];
    
    [imageData writeToFile:localFilePath1 atomically:YES];
    

    Hope it helps you.

    0 讨论(0)
提交回复
热议问题