gpt4 book ai didi

ios - 将 UIImage 以二进制形式保存到 SQLite 并使用 imageWithData 检索它

转载 作者:行者123 更新时间:2023-11-28 22:53:29 26 4
gpt4 key购买 nike

我正在将一些图像保存到我的应用程序中的 SQLite 数据库中。我使用图形化的 SQLite 客户端访问了数据库,它正确地保存了我的图像的二进制文件。问题在于从数据库中检索它。这是它的样子:

保存

-(void)insertObject:(Object *)object
{
const char* sqliteQuery = "INSERT INTO OBJECTS (OBJECTID, OBJECTIMAGE, OBJECTNAME) VALUES (?,?,?)";

sqlite3_stmt* statement;

if( sqlite3_prepare_v2(databaseHandle, sqliteQuery, -1, &statement, NULL) == SQLITE_OK )

{

sqlite3_bind_text(statement, 1, [object.id UTF8String], -1, SQLITE_TRANSIENT);

sqlite3_bind_blob(statement, 2, [object.imgData bytes], [object.imgData length], SQLITE_STATIC);

sqlite3_bind_text(statement, 3, [object.name UTF8String], -1, SQLITE_TRANSIENT);

sqlite3_step(statement);

}

else NSLog( @"SaveBody: Failed from sqlite3_prepare_v2. Error is: %s", sqlite3_errmsg(databaseHandle) );

sqlite3_finalize(statement);
}

检索

-(Object *)retrieveObjectWithID:(NSString*)id
{

NSString* sqliteQuery = [NSString stringWithFormat:@"SELECT OBJECTIMAGE,OBJECTNAME FROM OBJECTS WHERE OBJECTID = '%@'", id];
NSLog(@"sqlitequery: %@",sqliteQuery);
sqlite3_stmt* statement;

Object *object = [[Object alloc]init];

object.id = id;

if( sqlite3_prepare_v2(databaseHandle, [sqliteQuery UTF8String], -1, &statement, NULL) == SQLITE_OK )

{

if( sqlite3_step(statement) == SQLITE_ROW )

{

NSUInteger length = sqlite3_column_bytes(statement, 1);

object.imgData = [NSData dataWithBytes:sqlite3_column_blob(statement, 1) length:length];
object.name = [NSString stringWithFormat:@"%s",sqlite3_column_text(statement, 2)];

}

}


// Finalize and close database.

sqlite3_finalize(statement);


return object;
}

这是对象

@interface Object : NSObject


@property(nonatomic,strong) NSString *id;
@property(nonatomic,strong) NSString *name;
@property(nonatomic,strong) NSData *imgData;

@end

最佳答案

请检查以下代码,

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

object.imgData = data;

而不是,

NSUInteger length = sqlite3_column_bytes(statement, 1);

object.imgData = [NSData dataWithBytes:sqlite3_column_blob(statement, 1) length:length];

关于ios - 将 UIImage 以二进制形式保存到 SQLite 并使用 imageWithData 检索它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11316693/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com