如何在iphone中将十六进制值转换为blob

时间:2012-04-18 09:46:46

标签: iphone

在我的应用程序中,我有一个十六进制类型的图像; 我想转换为blob类型并保存到数据库;

怎么可能。

此致 K L BAIJU

1 个答案:

答案 0 :(得分:0)

根据我的知识它是base64编码的,假设你从web服务获得图像数据,你需要将接收到的字符串数据编码为base64编码。

NSData* data=[[NSData alloc] initWithBase64EncodedString:base64ImageString];

然后您可以轻松地将数据检索到UIImageView,

UIImageView* imageView=[[UIImageView alloc] initWithImage:[UIImage imageWithData:data]];

并将图像数据保存为sqlite,作为在片段

后面使用的Blob数据类型
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];        
 }  

的问候,
MAYUR