在我的应用程序中,我有一个十六进制类型的图像;我想转换为blob类型并保存到数据库;
怎么可能。
问候吉隆坡白酒
据我所知,它是 base64 编码的,假设如果您从 Web 服务获取图像数据,则需要将接收到的字符串数据编码为 base64 编码。
NSData* data=[[NSData alloc] initWithBase64EncodedString:base64ImageString];
然后您可以轻松地将数据检索到 UIImageView 中,
UIImageView* imageView=[[UIImageView alloc] initWithImage:[UIImage imageWithData:data]];
并将图像数据作为 Blob 数据类型保存到 sqlite 中,使用以下代码片段
if(insertStmt == nil) {
const char *sql = "insert into TableName values(?,?)";
if(sqlite3_prepare_v2(database, sql, -1, &insertStmt, NULL) != SQLITE_OK)
NSAssert1(0, @"Error while creating update statement. '%s'", sqlite3_errmsg(database));
}
sqlite3_bind_text(insertStmt, 1, [imageName UTF8String], -1, SQLITE_TRANSIENT);
NSData *imgData = UIImagePNGRepresentation(imageView.image);
int returnValue = -1;
returnValue = sqlite3_bind_blob(insertStmt, 2, [imgData bytes], [imgData length], NULL);
if(returnValue != SQLITE_OK)
NSLog(@"Not OK!!!");
if(SQLITE_DONE != sqlite3_step(insertStmt))
NSAssert1(0, @"Error while inserting. '%s'", sqlite3_errmsg(database));
sqlite3_reset(insertStmt);
[data release];
[imageView release];
从数据库中检索图像数据
if(detailStmt == nil) {
const char *sql = "Select * from TableName";
if(sqlite3_prepare_v2(database, sql, -1, &detailStmt, NULL) != SQLITE_OK)
NSAssert1(0, @"Error while creating detail view statement. '%s'", sqlite3_errmsg(database));
}
if(SQLITE_DONE != sqlite3_step(detailStmt)) {
NSData *data = [[NSData alloc] initWithBytes:sqlite3_column_blob(detailStmt, 2) length:sqlite3_column_bytes(detailStmt, 2)];
if(data == nil)
NSLog(@"No image found.");
else
imageview.image = [UIImage imageWithData:data];
}
问候,
马尤尔