我是iOS开发的新手,我正在尝试创建一个允许用户使用相机拍照的视图。
我想要发生的是当用户拍摄照片时,它会将其保存到相机胶卷中。我相信可以通过以下声明简单地完成:
//Let's say the image you want to save is in a UIImage called "imageToBeSaved"
UIImageWriteToSavedPhotosAlbum(imageToBeSaved, nil, nil, nil);
然而,我的问题是,如果用户离开视图然后返回到它,我仍然希望那张照片在那里。那么我如何取回之前拍摄/保存的相同图片,以便在重新打开视图时重新加载?
任何帮助都会很棒!谢谢。
答案 0 :(得分:0)
此代码段将从相机胶卷中获取最新图像:reference link
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
// Enumerate just the photos and videos group by using ALAssetsGroupSavedPhotos.
[library enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
// Within the group enumeration block, filter to enumerate just photos.
[group setAssetsFilter:[ALAssetsFilter allPhotos]];
// Chooses the photo at the last index
[group enumerateAssetsWithOptions:NSEnumerationReverse usingBlock:^(ALAsset *alAsset, NSUInteger index, BOOL *innerStop) {
// The end of the enumeration is signaled by asset == nil.
if (alAsset) {
ALAssetRepresentation *representation = [alAsset defaultRepresentation];
UIImage *latestPhoto = [UIImage imageWithCGImage:[representation fullScreenImage]];
// Stop the enumerations
*stop = YES; *innerStop = YES;
// Do something interesting with the AV asset.
[self sendTweet:latestPhoto];
}
}];
} failureBlock: ^(NSError *error) {
// Typically you should handle an error more gracefully than this.
NSLog(@"No groups");
}];
答案 1 :(得分:0)
void UIImageWriteToFile(UIImage *image, NSString *fileName)
{
NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectoryPath = dirPaths[0];
NSString *filePath = [documentDirectoryPath stringByAppendingPathComponent:fileName];
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:filePath atomically:YES];
}
void UIImageReadFromFile(UIImage **image, NSString *fileName)
{
NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectoryPath = dirPaths[0];
NSString *filePath = [documentDirectoryPath stringByAppendingPathComponent:fileName];
image = [UIImage imageWithContentsOfFile:filePath];
}
图像将以指定的名称保存到应用程序包的Documents目录中并从中读取。
用法示例:
UIImageWriteToFile(image, @"somephoto.png");
UIImage *fetchedImage;
UIImageReadFromFile(&fetchedImage, @"somephoto.png");