0

我在我的项目中使用 sqlite
以前我将图像保存在数据中,但现在我以字节为单位保存图像,如下面的代码

NSUInteger len = [entObject.photoImageData length];  
 Byte *byteData = (Byte*)malloc(len);  
 memcpy(byteData, [entObject.photoImageData bytes], len);  
insertString = [NSString stringWithFormat:@"INSERT INTO TBL_COUNTDOWN (DAIRYID,EVENTID,DESCRIPTION,EVENTIMAGE) VALUES (\"%@\",\"%d\",\"No Data\",\"%s\")",self.dairyId,self.eventId,byteData];

为了检索图像,我使用以下代码

NSData *dataForCachedImage = [[NSData alloc] initWithBytes:sqlite3_column_blob(statement, 3) length: sqlite3_column_bytes(statement, 3)];  
                    NSLog(@"dataForCachedImage/getAllEvents is %@",dataForCachedImage);  
                    UIImage *cachedImage = [UIImage imageWithData:dataForCachedImage];  
                    NSLog(@"cachedImage/getAllEvents is %@",cachedImage);

对于 NSLog 中的 dataForCachedImage 我正在获取数据,但对于 cachedImage 我得到 null

我的代码没有什么问题。请帮我

提前致谢

4

1 回答 1

1

您可以将图像保存到文档目录并将其路径存储到sqlite数据库保存图像代码如下

 #define DOCUMENTS_FOLDER [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]

 // Create a new dated file
 NSDate *now = [NSDate dateWithTimeIntervalSinceNow:0];
 NSString *caldate = [now description];

 NSString *filePath= [NSString stringWithFormat:@"%@/%@.jpg", DOCUMENTS_FOLDER,caldate];
 NSURL *url = [NSURL fileURLWithPath:filePath];

 UIImage *image = [UIImage imageNamed:@"name.jpg"];
 NSData *imageData = UIImagePNGRepresentation(image);

 [imageData writeToFile:filePath atomically:YES];

任何时候你想检索图像然后获取它然后使用以下方法获取图像

- (UIImage*)getImage
{
 NSString *imagePath = [DOCUMENTS_FOLDER stringByAppendingPathComponent:@"imagename.jpg"];
 UIImage *img = [UIImage imageWithContentsOfFile:imagePath];
 return img;
}

删除文件

  NSFileManager *fileManager=[NSFileManager defaultManager];
  [fileManager removeItemAtPath:savedFilePath error:nil];

这可能会帮助你..

于 2012-12-27T07:24:26.863 回答