我知道这个问题被很多人问过,关于“为什么要使用 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常见的答案是将图像保存在应用程序的文档目录中,而在数据库中仅保存图像的路径。
因为在数据库中插入 blob 会使我们的数据库非常非常慢:(
但是我该怎么做。我无法理解我正确浏览过的链接中的代码片段,如何将 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);
请帮帮我,在如何处理和继续处理这个问题上苦苦挣扎:(
提前致谢:)
最佳答案
保存图片到文档
- (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];
}
关于iphone - 将图像存储到sqlite数据库中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10811437/