【问题标题】:How to add image to sql ? I have converted image to NSdata如何将图像添加到 sql 中?我已将图像转换为 NSdata
【发布时间】:2017-06-10 10:29:19
【问题描述】:

这是查询

-(void)runQuery:(const char *)query isQueryExecutable:(BOOL)queryExecutable{
// Create a sqlite object.
sqlite3 *sqlite3Database;

// Set the database file path.
NSString *databasePath = [self.documentsDirectory stringByAppendingPathComponent:self.databaseFilename];

// Initialize the results array.
if (self.arrResults != nil) {
    [self.arrResults removeAllObjects];
    self.arrResults = nil;
}
self.arrResults = [[NSMutableArray alloc] init];

// Initialize the column names array.
if (self.arrColumnNames != nil) {
    [self.arrColumnNames removeAllObjects];
    self.arrColumnNames = nil;
}
self.arrColumnNames = [[NSMutableArray alloc] init];


// Open the database.
BOOL openDatabaseResult = sqlite3_open([databasePath UTF8String], &sqlite3Database);
if(openDatabaseResult == SQLITE_OK) {
    // Declare a sqlite3_stmt object in which will be stored the query after having been compiled into a SQLite statement.
    sqlite3_stmt *compiledStatement;

    // Load all data from database to memory.
    BOOL prepareStatementResult = sqlite3_prepare_v2(sqlite3Database, query, -1, &compiledStatement, NULL);
    if(prepareStatementResult == SQLITE_OK) {
        // Check if the query is non-executable.
        if (!queryExecutable){
            // In this case data must be loaded from the database.

            // Declare an array to keep the data for each fetched row.
            NSMutableArray *arrDataRow;

            // Loop through the results and add them to the results array row by row.
            while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
                // Initialize the mutable array that will contain the data of a fetched row.
                arrDataRow = [[NSMutableArray alloc] init];

                // Get the total number of columns.
                int totalColumns = sqlite3_column_count(compiledStatement);

                // Go through all columns and fetch each column data.
                for (int i=0; i<totalColumns; i++){
                    // Convert the column data to text (characters).
                    char *dbDataAsChars = (char *)sqlite3_column_text(compiledStatement, i);

                    // If there are contents in the currenct column (field) then add them to the current row array.
                    if (dbDataAsChars != NULL) {
                        // Convert the characters to string.
                        [arrDataRow addObject:[NSString  stringWithUTF8String:dbDataAsChars]];
                    }

                    // Keep the current column name.
                    if (self.arrColumnNames.count != totalColumns) {
                        dbDataAsChars = (char *)sqlite3_column_name(compiledStatement, i);
                        [self.arrColumnNames addObject:[NSString stringWithUTF8String:dbDataAsChars]];
                    }
                }

                // Store each fetched data row in the results array, but first check if there is actually data.
                if (arrDataRow.count > 0) {
                    [self.arrResults addObject:arrDataRow];
                }
            }
        }
        else {
            // This is the case of an executable query (insert, update, ...).

            // Execute the query.
            BOOL executeQueryResults = sqlite3_step(compiledStatement);
            if (executeQueryResults == SQLITE_DONE) {
                // Keep the affected rows.
                self.affectedRows = sqlite3_changes(sqlite3Database);

                // Keep the last inserted row ID.
                self.lastInsertedRowID = sqlite3_last_insert_rowid(sqlite3Database);
            }
            else {

                NSLog(@"DB Error: %s", sqlite3_errmsg(sqlite3Database));
            }
        }
    }
    else {

        NSLog(@"%s", sqlite3_errmsg(sqlite3Database));
    }


    sqlite3_finalize(compiledStatement);

}


sqlite3_close(sqlite3Database);
}

我正在插入值

NSString *query;
if (self.recordIDToEdit == -1) {
    query = [NSString stringWithFormat:@"insert into peopleInfo values(null, '%@', '%@', %d )", self.txtFirstname.text, self.txtLastname.text, [self.txtAge.text intValue]];

}
else{
    query = [NSString stringWithFormat:@"update peopleInfo set firstname='%@', lastname='%@', age=%d where peopleInfoID=%d", self.txtFirstname.text, self.txtLastname.text, self.txtAge.text.intValue, self.recordIDToEdit];
}

【问题讨论】:

  • 与其将图片保存到数据库,不如将图片作为文件保存到documents文件夹,并保存图片在数据库中的路径

标签: ios objective-c iphone sqlite


【解决方案1】:

您只是不需要在数据库中添加图像。将您的图像放在 HomeDirectory 中,然后将 ImageUrl 保存在数据库中。这样您就可以轻松管理它。

【讨论】:

    【解决方案2】:

    我给你详细的答案。如果要将图像保存到数据库中,请先将图像保存到文档目录中,然后将文档目录路径传递给 SQLite db。

    我有单独的文件(NSObject 类)用于将图像保存到文档目录中。

    PhotoPath.h

    #import <Foundation/Foundation.h>
    #import <UIKit/UIKit.h>
    
    @interface PhotoPath : NSObject
    
    +(NSString*)getSavedPhotoPath:(UIImage*)image;
    +(NSString*)getphotopath;
    +(NSString *)applicationDocumentsdirectory;
    +(void)ensureDirs:(NSString*)path;
    +(NSString*)getCurrentTime;
    +(NSString*)getCurrentDate;
    
    @end 
    

    PhotoPath.m

    #import "PhotoPath.h"
    
    @implementation PhotoPath
    
    +(NSString*)getSavedPhotoPath:(UIImage*)image
    {
        NSString *path =nil;
        NSString *file_name = [[self getCurrentDate]stringByAppendingString:[self getCurrentTime]];
        file_name =[file_name stringByAppendingPathExtension:@"jpeg"];
        path =[[self getphotopath]stringByAppendingPathComponent:file_name];
        NSData *imgData =UIImageJPEGRepresentation(image, 0.4);
        [imgData writeToFile:path atomically:YES];
        return path;
    }
    
    +(NSString*)getphotopath
    {
        //CREATE PHOTO PATH FOR SAVED IMAGES
        NSString *path = [[self applicationDocumentsdirectory]stringByAppendingPathComponent:@"photosOne"];
        [self ensureDirs:path];
        return path;
    }
    
    +(NSString *)applicationDocumentsdirectory
    {
        int i=0;
        NSArray *paths1 =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *basePath =([paths1 count] >i) ? [paths1 objectAtIndex:i] : nil;
        return basePath;
    }
    
    +(void)ensureDirs:(NSString*)path
    {
        //Get Directory in FileManager
        NSFileManager *fileManager =[NSFileManager defaultManager];
        if ([fileManager fileExistsAtPath:path])
         return;
       [fileManager createDirectoryAtPath:path  withIntermediateDirectories:NO attributes:nil error:nil];
    }
    
    +(NSString*)getCurrentTime
    {
        //Get Current Time for saving Images
        NSString *path =nil;
        NSDateFormatter *timeFormatter =[[NSDateFormatter alloc]init];
        [timeFormatter setDateFormat:@"HH:mm:ss.SSS"];
        NSDate *now = [[NSDate alloc]init];
        NSString *str_time = [timeFormatter stringFromDate:now];
        NSString *curr_time;
        curr_time =[str_time stringByReplacingOccurrencesOfString:@"." withString:@""];
        path = [NSString stringWithFormat:@"%@",curr_time];
        return  path;
    }
    
    +(NSString*)getCurrentDate
    {
        NSString *today =nil;
        NSDateFormatter *dateFormatter1;
        dateFormatter1 =[[NSDateFormatter alloc]init];
        [dateFormatter1 setDateFormat:@"d MMM yyyy"];
        NSDate *now =[[NSDate alloc]init];
        NSLocale *usLocale =[[NSLocale alloc]initWithLocaleIdentifier:@"en_US"];
        [dateFormatter1 setLocale:usLocale];
        NSString *str_date =[dateFormatter1 stringFromDate:now];
        today=[NSString stringWithFormat:@"%@",str_date];
        return today;
    }
    
    @end
    

    ViewController.h

    #import <UIKit/UIKit.h>
    #import "PhotoPath.h"
    @interface ViewController : UIViewController<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
    {
       PhotoPath *path;
    }
    @property(nonatomic,retain)NSMutableArray *arrImg;
    @property (strong, nonatomic) IBOutlet UIImageView *imgPick;
    - (IBAction)actionSaveImageIntoSQLite:(id)sender;
    @end
    

    ViewController.m

    #import "ViewController.h"
    interface ViewController ()
    @end
    @implementation ViewController
    @synthesize arrImg,imgPick;
    
    - (void)viewDidLoad
    {
      [super viewDidLoad];
       UITapGestureRecognizer *tapImage =[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapDetect)];
       tapImage.numberOfTapsRequired =1;
       tapImage.numberOfTouchesRequired =1;
       imgPick.userInteractionEnabled =YES;
       [imgPick addGestureRecognizer:tapImage];
    }
    
    -(void)tapDetect
    {
        UIImagePickerController *picker =[[UIImagePickerController alloc]init];
        picker.sourceType =UIImagePickerControllerSourceTypePhotoLibrary;
        picker.delegate =self;
        [self presentViewController:picker animated:NO completion:nil];
    }
    - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
    {
        UIImage *image=[info objectForKey:@"UIImagePickerControllerOriginalImage"];
        imgPick.image=image;
        [arrImg addObject:image];
        picker.delegate =self;
        [picker dismissViewControllerAnimated:YES completion:nil];
    }
    - (IBAction)actionSaveImageIntoSQLite:(id)sender
    {
       NSMutableArray *arrAllImgPath =[[NSMutableArray alloc]init];
       for (UIImage *img in arrImg)
       {
          NSString *strImgPath =[PhotoPath getSavedPhotoPath:img];
          [arrAllImgPath addObject:strImgPath];
       }
       NSLog(@"The path is - %@",arrAllImgPath);
       for (int i=0; i<[arrAllImgPath count]; i++)
       {
          NSString *strImgPathURL = [arrAllImgPath objectAtIndex:i];
          [SqliteDB insertDataintoDB:strImgPathURL];
       }
    }
    @end
    

    当你从 SQLite DB 获取图像时

    NSString *localPath=[NSString stringWithFormat:@"%@",[arrSQLiteDBImg objectAtIndex:i]];
    NSURL *urlString=[NSURL fileURLWithPath:localPath];
    NSData *data = [NSData dataWithContentsOfURL:urlString];
    UIImage *img = [[UIImage alloc] initWithData:data] ;         
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-20
      • 1970-01-01
      • 2014-09-22
      • 2013-10-05
      • 1970-01-01
      • 2015-10-11
      • 2017-03-30
      相关资源
      最近更新 更多