我知道很多人都提出了这个问题,并且有几个关于“为什么要使用sqlite,使用FMDB,核心数据”等的讨论和论据来存储或插入数据库中的图像。但请理解我的问题我非常习惯sqlite3,我无法使用核心数据或其他数据库。我也只是在学习iphone技术的阶段。所以我请求我提供一个只能用sqlite处理的解决方案;)
如果我的请求中有任何错误,请道歉!
我有一个文本字段,可以在输入字母时显示表格,即。来自联系人,如果我输入字母“L”,“Lakshaman Rao,Prasanna Lakshmi”,“Lokesh Sharan”等等。
现在我正在尝试从相应的联系人那里获取相应的联系人图片。所以我搜索了有关如何检索联系人图像的代码示例,并采用以下方式实现:
NSData *imgData = nil;
imgData = (NSData *)ABPersonCopyImageData(ref);
contactImage = [UIImage imageWithData:imgData];
现在我搜索了类似的问题here和there,常见的答案是将图像保存在应用程序的文档目录中,并在数据库中仅保存图像的路径。
因为在db中插入blob会使我们的db非常慢:(
但是我该怎么做。我无法理解我正确经历的链接中的代码片段,如何将UIImage类型的contactImage转换为NSString,以便我可以将字符串插入数据库将记录保存为VARCHAR类型的表!
修改
这是在那里建议的代码:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent:@"savedImage.png"];
UIImage *img = [UIImage imageWithContentsOfFile:getImagePath];
这是我实施的代码:
ABAddressBookRef addressBook = ABAddressBookCreate( );
CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople( addressBook );
CFIndex nPeople = ABAddressBookGetPersonCount( addressBook );
NSString *contactFirstName = nil;
NSString *contactLastName = nil;
NSString *fullName = nil;
for ( int i = 0; i < nPeople; i++ )
{
ref = CFArrayGetValueAtIndex( allPeople, i );
contactFirstName = [[[NSString alloc] initWithString:(NSString *)ABRecordCopyValue(ref, kABPersonFirstNameProperty)]autorelease];
contactLastName = [[[NSString alloc] initWithString:(NSString *)ABRecordCopyValue(ref, kABPersonLastNameProperty)]autorelease];
contactLastName = [NSString stringWithFormat:@" %@",contactLastName];
fullName = [contactFirstName stringByAppendingString:contactLastName];
[contactList addObject:fullName];
}
NSData *imgData = nil;
imgData = (NSData *)ABPersonCopyImageData(ref);
contactImage = [UIImage imageWithData:imgData];
CFRelease(allPeople);
CFRelease(addressBook);
请帮助我,努力解决如何处理并继续这样做:(
提前感谢所有人:)
答案 0 :(得分:6)
将图像保存到文档
- (void)saveImage:(UIImage *)image forPerson:(NSString *)fullName {
// Make file name first
NSString *filename = [fullName stringByAppendingString:@".png"]; // or .jpg
// Get the path of the app documents directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
// Append the filename and get the full image path
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:filename];
// Now convert the image to PNG/JPEG and write it to the image path
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:savedImagePath atomically:NO];
// Here you save the savedImagePath to your DB
...
}
所以,你以后可以通过
获取图像- (UIImage *)loadImage:(NSString *)filePath {
return [UIImage imageWithContentsOfFile:filePath];
}