【问题标题】:How to store image in sqlite database in iphone? [closed]如何将图像存储在 iPhone 的 sqlite 数据库中? [关闭]
【发布时间】:2013-03-07 05:06:20
【问题描述】:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"image.sqlite"];


    if (sqlite3_open_v2([path UTF8String], &database, SQLITE_OPEN_READWRITE, NULL) == SQLITE_OK)
    {


        if(selectStmt == nil)
        {
            const char *sql = "insert into imagetb(imagename,image) Values(?,?)";
            if(sqlite3_prepare_v2(database, sql, -1, &selectStmt, NULL) != SQLITE_OK)
                //              NSAssert1(0, @"Error while creating add statement. '%s'", sqlite3_errmsg(database));
                NSLog(@"%s",sqlite3_errmsg(database));
        }



        sqlite3_bind_text(selectStmt, 1, [@"test.png" UTF8String], -1, SQLITE_TRANSIENT);

         sqlite3_bind_blob(selectStmt, 2, [data1 bytes], [data1 length], SQLITE_TRANSIENT);

        if(SQLITE_DONE != sqlite3_step(selectStmt))
            NSLog(@"get: %s",sqlite3_errmsg(database));
        else
            NSLog(@"scan data added");


    }

    //showimage
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];


    if (sqlite3_open([path UTF8String], &database) == SQLITE_OK)
    {
        const char *sql = "select * from imagetb";// LIMIT 0,100 ";// where status = 1 ";
        sqlite3_stmt *selectstatment;

        if (sqlite3_prepare_v2(database, sql, -1, &selectstatment, NULL) == SQLITE_OK)
        {
            while (sqlite3_step(selectstatment) == SQLITE_ROW)
            {

                NSString *getorgstrid = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstatment, 0)];
                NSLog(@"id->%@",getorgstrid);

                [getid addObject:getorgstrid];

                NSString *getorgstrname = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstatment, 1)];
                NSLog(@"name->%@",getorgstrname);
                [getname addObject:getorgstrname];


                NSData *getorgstrimage = [[NSData alloc] initWithBytes:sqlite3_column_blob(selectstatment,2)length:sqlite3_column_bytes(selectstatment, 2)];

                [getimage addObject:getorgstrimage];

            }
        }
        sqlite3_finalize(selectstatment);

    }
    //[tblorgland reloadData];

    UIImage *image1 = [UIImage imageWithData:[getimage lastObject]];

    NSLog(@"image%@",image1);

    [getImageview setImage:image1];
    [pool release];


==============================================================================

- (NSString *) getDBPath
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
    NSString *documentsDir = [paths objectAtIndex:0];

    return [documentsDir stringByAppendingPathComponent:@"image.sqlite"];
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    getid=[[NSMutableArray alloc]init];
    getname=[[NSMutableArray alloc]init];
    getimage=[[NSMutableArray alloc]init];

    [self downloadimage];
    [self makeDBCopyAsNeeded];
}
-(void)downloadimage
{
    NSLog(@"Downloading...");

    UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://0.tqn.com/d/graphicssoft/1/7/g/A/5/psptubezdotcom_003.png"]]];

    NSLog(@"%f,%f",image.size.width,image.size.height);


    NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];


    NSLog(@"%@",docDir);

    NSLog(@"saving png");
    pngFilePath = [NSString stringWithFormat:@"%@/test.png",docDir];
    data1 = [NSData dataWithData:UIImagePNGRepresentation(image)];

    img=[[UIImage alloc]initWithData:data1];



    [data1 writeToFile:pngFilePath atomically:YES];


    NSLog(@"saving jpeg");
    NSString *jpegFilePath = [NSString stringWithFormat:@"%@/test.jpeg",docDir];

    NSLog(@"jpegFilePath:%@",jpegFilePath);
    data2 = [NSData dataWithData:UIImageJPEGRepresentation(image, 1.0f)];

    [data2 writeToFile:jpegFilePath atomically:YES];

    NSLog(@"saving image done");

    [image release];


}
- (void) makeDBCopyAsNeeded
{
    BOOL success;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"image.sqlite"];
    success = [fileManager fileExistsAtPath:writableDBPath];

    NSString *dbPath = [self getDBPath];
    NSLog(@"%@",dbPath);

    if (success)
    {
        NSLog(@"Database Success Created");
        return;
    }
    NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"image.sqlite"];
    success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
    if (!success)
    {
        NSLog(@"Database:->%s",sqlite3_errmsg(database));
    }
}

【问题讨论】:

  • 您可以将图像的路径存储到数据库中,而不是存储整个图像
  • 看看 SO 问题 :stackoverflow.com/questions/5039343/… 。希望这会对你有所帮助。
  • 将图像写入文件系统要好得多。您可以引用数据库中的文件名。
  • S 最好将图像存储在 Document 目录中,并使用一些唯一的 id 作为图像名称,以便更好地使用..
  • 我会存储图片的地址。当需要将图片加载到 UIImageView 时,使用 imageWithContentsOfFile 将图片加载到 UIImageView

标签: iphone ios objective-c sqlite


【解决方案1】:

不建议将图片数据存储在sqlite中。但是如果你想存储图像数据然后使用这个链接

Save image data to sqlite database in iphone

希望对你有帮助..

【讨论】:

    【解决方案2】:

    你最好使用缓存来存储你的图片,并使用数据库来存储他们的名字或一些唯一的ID

    【讨论】:

    • 可以清除缓存目录。那不是存储无法替换的数据的好地方。
    • 而不是存储图像数据,您应该使用将图像名称存储在数据库中。因此它将减少从数据库存储和获取的时间
    【解决方案3】:

    只需在 -(void)imagePickerController:(UIImagePickerController *)picker 中编写以下代码 didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo: 如果你从画廊或相机中获取图像,否则跳过 if (imageData != nil) 下的代码,只需使用下面的代码将图像保存在 sqlite 中

    NSData * imageData = UIImageJPEGRepresentation(image, 0.8);
        NSLog(@"Image data length== %d",imageData.length);
    
    if (imageData != nil)
        {
            UIImage *resizedImg = [self scaleImage:[UIImage imageWithData:imageData] toSize:CGSizeMake(150.0f,150.0f)];
    
            NSData * imageData = UIImageJPEGRepresentation(resizedImg, 0.2);
            NSLog(@"*** Image data length after compression== %d",imageData.length);
    
            NSString *nameofimg=[NSString stringWithFormat:@"%@",resizedImg];
    
            NSString *substring=[nameofimg substringFromIndex:12];
            NSString *new=[substring substringToIndex:7];// Get image name
    
            NSArray *path=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    
            NSString *documentdirectory=[path objectAtIndex:0];
    
            NSString *newFilePath = [NSString stringWithFormat:[documentdirectory stringByAppendingPathComponent: @"/%@.png"],new];
    
            [imageData writeToFile:newFilePath atomically:YES];
    
            imgpath=[[NSString alloc]initWithString:newFilePath];
            NSLog(@"doc img in img method === %@",imgpath);
        }
    
    
         databasepath=[app getDBPath]; // i have this method in delegate
            if (sqlite3_open([databasepath UTF8String], &dbAssessor) == SQLITE_OK)
            {
                NSString *selectSql = [NSString stringWithFormat:@"insert into imagetb(imagename,image) VALUES(\"%@\",\"%@\") ;",yourImgName,imgpath];
    
                NSLog(@"Query : %@",selectSql);
    
                const char *sqlStatement = [selectSql UTF8String];
                sqlite3_stmt *query_stmt;
                sqlite3_prepare(dbAssessor, sqlStatement, -1, &query_stmt, NULL);
    
                if(sqlite3_step(query_stmt)== SQLITE_DONE)
                {
                    NSLog(@"home image updated. :)");
                    app.houseImage=imgpath;
                }
                else
                {
                    UIAlertView *alert = [[UIAlertView alloc]
                                          initWithTitle:@"Sorry" message:@"Failed To Save Home Image." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
                    [alert show];
                    [alert release];
                }
                sqlite3_finalize(query_stmt);
            }
            sqlite3_close(dbAssessor);
    

    【讨论】:

    • 这个问题与从图像选择器中选择图像有什么关系?
    猜你喜欢
    • 2023-03-19
    • 1970-01-01
    • 2012-03-10
    • 1970-01-01
    • 1970-01-01
    • 2012-08-01
    • 2012-06-14
    相关资源
    最近更新 更多