【问题标题】:Sqlite3 Blob to UIImageSqlite3 Blob 到 UIImage
【发布时间】:2011-09-28 04:08:03
【问题描述】:

您好,我在我的计算机中创建了一个 Sqlite3 数据库,我想在我的 Iphone 中读取该数据库。 以下代码适用于 Iphone 模拟器,但不适用于真实设备,这似乎是与设备架构(MacBook vs Iphone)相关的一些问题。 问题是当我读取数据并尝试将其转换为 UIImage 时,数据似乎不正确,因为结果是空白的 UIImageView 而不是图像的表示。在模拟器中效果很好。

-(IBAction) findPhoto{

databaseName = @"memoryDB.sqlite";

    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDir = [documentPaths objectAtIndex:0];
    databasePath = [documentsDir stringByAppendingPathComponent:databaseName];



    int res = 0;

    res = sqlite3_open_v2([databasePath UTF8String], &database, SQLITE_OPEN_READONLY, nil);

    if(res == SQLITE_OK) {
        // Setup the SQL Statement and compile it for faster access

        NSString *querySQL = [NSString stringWithString:@"SELECT * FROM Fotos"];

        const char *sqlStatement = [querySQL UTF8String];

        sqlite3_stmt *compiledStatement;
        if((res = sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL)) == SQLITE_OK) {
            // Loop through the results and add them to the feeds array
            while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
                // Read the data from the result row


                UIImage *image;

                NSData *data = [[NSData alloc] initWithBytes:sqlite3_column_blob(compiledStatement, 1) length:sqlite3_column_bytes(compiledStatement, 1)];

                if(data == nil)
                    NSLog(@"No image found.");
                else
                    image = [[UIImage alloc] initWithData:data];     
                //

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

                UIImageView *imgView = [[UIImageView alloc] initWithImage:image];
                [self.view addSubview:imgView];

            }
        }
        // Release the compiled statement from memory
        sqlite3_finalize(compiledStatement);
        sqlite3_close(database); 

    }
}

我在项目中包含数据库 (DB),并且该数据库是在我的 MacBook 中创建的。那是问题吗?是否可以将数据转换为正确的格式?

【问题讨论】:

    标签: iphone objective-c sqlite uiimage blob


    【解决方案1】:

    这不是正确的方法。将图像存储在数据库中。

    你应该把它保存到 NSDocumentDirectory。

    只需将图片名称存入db表即可。

    所以很容易从表中获取图像名称并从文档目录中获取图像。而且它比从数据库获取图像要快得多。

    【讨论】:

    • 谢谢。我会尝试,但我的应用程序大小有一些问题。我希望它小于 20 MB。按照你的建议去做,我会有照片的路径,我会有照片……而不是只有照片
    • 如果你将它存储在数据库中,那么它也会增加数据库的大小。
    • 我不认为将原始二进制数据存储在数据库中是不正确的。这就是 BLOB(以及 TINYBLOB、MEDIUMBLOB 等)存在的原因。当然,它有它的缺点,但它有时会有所帮助,而且它是在某些情况下应该使用的资源。
    猜你喜欢
    • 2017-03-10
    • 2011-05-12
    • 2011-04-29
    • 2011-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-31
    相关资源
    最近更新 更多