【问题标题】:Can't display image from sqlite database (blob) in iphone无法在 iPhone 中显示来自 sqlite 数据库(blob)的图像
【发布时间】:2015-05-03 03:23:57
【问题描述】:

我正在尝试显示我的 sqlite 数据库中的图像(作为 blob),它通过显示图像的长度和 NSLog:"Image FOUND" 知道图像文件在那里,但它没有加载图像视图中的图像。我已经尝试了许多来自 stackoverflow 的示例,例如 this one 等等,但仍然没有问题。在此先感谢各位。这是我到目前为止得到的:

sqlite3_stmt *statement1;

NSString *querySQL1 = [NSString stringWithFormat:@"SELECT picture FROM table1 WHERE var = %f", variable];

const char *query_statement1 = [querySQL1 UTF8String];

if(sqlite3_prepare_v2(_DB, query_statement1, -1, &statement1, nil) == SQLITE_OK)
{

    if (sqlite3_step(statement1) == SQLITE_ROW)
    {

    int length = sqlite3_column_bytes(statement1, 0);

    NSData *data = [[NSData alloc] initWithBytes:sqlite3_column_blob(statement1, 0) length:length];

        UIImage *image = [UIImage imageWithData:data];

        NSLog(@"Length : %d", [data length]);

        if(data == nil)
            {
                NSLog(@"No image found.");
            }

        else
            {
                NSLog(@"image FOUND .");
                myImageView.image = image;       
            }   
    }

}

【问题讨论】:

  • 仅仅因为 data != nil 并不意味着它包含 [UIImage imageWithData] 将处理的有效图像数据(即 PNG 或 JPG 图像)。检查是否 (image == nil) 代替。如果您看到 nil,请查看数据的内容。
  • 刚刚尝试过,它返回:图像已找到,但在图像视图中仍不显示任何内容。
  • 可能有很多东西。正如 CSmith 所说,您从数据库中检索到的图像可能不是有效图像。除了测试data 是否为nil,还要检查image 是否为nil。如果那是nil,那么问题出在数据库中的数据上。如果不是nil,那么它就是别的东西(例如,可能myImageViewnil 或者它的frame 是这样的,你看不到它)。
  • 成功了,伙计们!!!问题在于你们都提到的两件事。现在工作正常。非常感谢
  • 如果你认为你的发现对未来的用户有用,post an answer to your own question 概述它是什么。或者,更好的是,邀请 CSmith 发布答案。但是,如果该解决方案不太可能对未来的用户有用(例如,这只是一些愚蠢的错误),那么也许只是删除这个问题

标签: ios database image sqlite blob


【解决方案1】:
sqlite3 *dataname1;

if (sqlite3_open([datapath UTF8String],&dataname1) == SQLITE_OK) {

    const char *sqlStatement;

    sqlStatement = "SELECT * FROM photography_tips";


    sqlite3_stmt *compiledStatement;

    if(sqlite3_prepare_v2(dataname1, 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
        NSData *data = [[NSData alloc] initWithBytes:sqlite3_column_blob(compiledStatement, 2) length:sqlite3_column_bytes(compiledStatement, 2)];
            [tipimage addObject:data];

        }

    }
NSLog(@"%@", tiptittle);
}

然后在cellforrowatindexpath方法中添加如下代码

 NSData *data= (NSData *) [tipimage objectAtIndex:indexPath.row];
cell.imageView.image=[UIImage imageWithData:data];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-16
    • 1970-01-01
    • 1970-01-01
    • 2016-11-23
    • 2012-02-03
    • 1970-01-01
    • 2015-05-25
    相关资源
    最近更新 更多