iPhone: Как получить путь к файлу изображения, сохраненного с помощью UIImageWriteToSavedPhotosAlbum()?
Я сохраняю объединенное изображение в библиотеке фотографий iPhone, используя:
UIImageWriteToSavedPhotosAlbum(viewImage, self, @selector(savedPhotoImage:didFinishSavingWithError:contextInfo:), nil);
И получить обратный вызов, используя:
- (void) savedPhotoImage:(UIImage*)image didFinishSavingWithError:(NSError *)error contextInfo: (void *)contextInfo { NSLog(@"%@", [error localizedDescription]);
NSLog(@"info: %@", contextInfo);}
То, что я хотел бы получить, - это путь к месту сохранения изображения, поэтому я могу добавить его в массив, который будет использоваться для вызова списка сохраненных элементов в другом месте приложения.
Когда я загружаю изображение с помощью средства выбора, оно отображает информацию о пути. Однако, когда я сохраняю созданное изображение, я не могу найти, куда можно потянуть путь к сохраненному изображению.
У меня есть поиск по сети, но большинство примеров останавливаются на обратном вызове с хорошим сообщением о том, что изображение было успешно сохранено. Я просто хотел бы знать, где он был сохранен.
Я понимаю, что один из методов может состоять в том, чтобы начать определять свои собственные пути, но так как метод делает это для меня, я просто надеялся, что он скажет мне, куда он был сохранен.
7 ответов
Я наконец узнал ответ. По-видимому, методы UIImage удаляют метаданные, поэтому использование UIImageWriteToSavedPhotosAlbum бесполезно.
Однако в ios4 Apple добавила новую платформу для работы с библиотекой фотографий, которая называется ALAssetsLibrary.
Сначала вам нужно щелкнуть правой кнопкой мыши на Targets и в части сборки добавить AlAsset Framework в ваш проект с маленьким значком + в левом нижнем углу.
Затем добавьте #import "AssetsLibrary/AssetsLibrary.h";
в заголовочный файл вашего класса.
Наконец, вы можете использовать следующий код:
UIImage *viewImage = YOUR UIIMAGE // --- mine was made from drawing context
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
// Request to save the image to camera roll
[library writeImageToSavedPhotosAlbum:[viewImage CGImage] orientation:(ALAssetOrientation)[viewImage imageOrientation] completionBlock:^(NSURL *assetURL, NSError *error){
if (error) {
NSLog(@"error");
} else {
NSLog(@"url %@", assetURL);
}
}];
[library release];
И это дает путь к файлу, который вы только что сохранили.
В ответе OlivariesF отсутствует ключевая часть этого вопроса, найдите путь:
Вот фрагмент кода, который делает все:
- (void)processImage:(UIImage*)image type:(NSString*)mimeType forCallbackId:(NSString*)callbackId
{
__block NSString* localId;
// Add it to the photo library
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
PHAssetChangeRequest *assetChangeRequest = [PHAssetChangeRequest creationRequestForAssetFromImage:image];
localId = [[assetChangeRequest placeholderForCreatedAsset] localIdentifier];
} completionHandler:^(BOOL success, NSError *err) {
if (!success) {
NSLog(@"Error saving image: %@", [err localizedDescription]);
} else {
PHFetchResult* assetResult = [PHAsset fetchAssetsWithLocalIdentifiers:@[localId] options:nil];
PHAsset *asset = [assetResult firstObject];
[[PHImageManager defaultManager] requestImageDataForAsset:asset
options:nil
resultHandler:^(NSData *imageData, NSString *dataUTI, UIImageOrientation orientation, NSDictionary *info) {
NSURL *fileUrl = [info objectForKey:@"PHImageFileURLKey"];
if (fileUrl) {
NSLog(@"Image path: %@", [fileUrl relativePath]);
} else {
NSLog(@"Error retrieving image filePath, heres whats available: %@", info);
}
}];
}
}];
}
Мой код
-(void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
UIImage *image = [info valueForKey:UIImagePickerControllerOriginalImage];
imageURL = nil;
ALAssetsLibraryWriteImageCompletionBlock completeBlock = ^(NSURL *assetURL, NSError *error){
if (!error) {
#pragma mark get image url from camera capture.
imageURL = [NSString stringWithFormat:@"%@",assetURL];
}
};
if(image){
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library writeImageToSavedPhotosAlbum:[image CGImage]
orientation:(ALAssetOrientation)[image imageOrientation]
completionBlock:completeBlock];
}
}
в.h импортировать библиотеку и определить тип def для ALAssetsLibraryWriteImageCompletionBlock
#import <UIKit/UIKit.h>
#import <AssetsLibrary/AssetsLibrary.h>
typedef void (^ALAssetsLibraryWriteImageCompletionBlock)(NSURL *assetURL, NSError *error);
если вы не знаете, как получить <AssetsLibrary/AssetsLibrary.h>
пожалуйста, добавьте существующий фреймворк (AssetsLibrary.framework)
Swift 4.1 версия ответа OlivaresF
PHPhotoLibrary.shared().performChanges({
PHAssetChangeRequest.creationRequestForAsset(from: image)
}) { (success, error) in
if success {
} else {
}
}
Быстрая версия будет
ALAssetsLibrary().writeImageToSavedPhotosAlbum(editedImage.CGImage, orientation: ALAssetOrientation(rawValue: editedImage.imageOrientation.rawValue)!,
completionBlock:{ (path:NSURL!, error:NSError!) -> Void in
print("\(path)")
})
И "импортировать ALAssetsLibrary" в вашем файле.
Проект-> Фазы сборки -> Бинарный файл ссылки -> AssetsLibrary.framework
ALAssetsLibrary устарела.
Вот как вы должны это сделать:
#import <Photos/Photos.h>
UIImage *yourImage;
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
[PHAssetChangeRequest creationRequestForAssetFromImage:yourImage];
} completionHandler:^(BOOL success, NSError *error) {
if (success) {
NSLog(@"Success");
} else {
NSLog(@"write error : %@",error);
}
}];
Свифт версия
var localId = ""
PHPhotoLibrary.shared().performChanges({
let assetChangeRequest:PHAssetChangeRequest = PHAssetChangeRequest.creationRequestForAsset(from: chosenImage)
localId = assetChangeRequest.placeholderForCreatedAsset!.localIdentifier
}) { (success, error) in
let assetResult:PHFetchResult = PHAsset.fetchAssets(withLocalIdentifiers: [localId], options: nil)
let asset:PHAsset = assetResult.firstObject!
PHImageManager.default().requestImageData(for: asset, options: nil) { (imageData, dataUTI, orientation, info) in
if let url:URL = info?["PHImageFileURLKey"] as? URL
{
print("\(url)")
}
}
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)img editingInfo:(NSDictionary *)editInfo {
RandomIndexnew = arc4random() % 3;
if(RandomIndexnew == 0)
{
nameStr =[NSString stringWithFormat:@"jpg"];
textFieldNormalFile_type.text =[NSString stringWithFormat:@"jpg"];
}
else if(RandomIndexnew = 1)
{
nameStr =[NSString stringWithFormat:@"gif"];
textFieldNormalFile_type.text =[NSString stringWithFormat:@"GIF"];
}
else if(RandomIndexnew = 2)
{
nameStr =[NSString stringWithFormat:@"jpg"];
textFieldNormalFile_type.text =[NSString stringWithFormat:@"JPG"];
}
RandomIndex = arc4random() % 20;
NSString *nameStr1 =[NSString stringWithFormat:@"Image%i",RandomIndex];
textFieldNormalFile_name.text =[NSString stringWithFormat:@"%@.%@",nameStr1,nameStr];
newFilePath = [NSHomeDirectory() stringByAppendingPathComponent: textFieldNormalFile_name.text];
imageData = UIImageJPEGRepresentation(img, 1.0);
if (imageData != nil) {
NSLog(@"HERE [%@]", newFilePath);
[imageData writeToFile:newFilePath atomically:YES];
}
image.image =[UIImage imageNamed:newFilePath];
NSLog(@"newFilePath:%@",newFilePath);
path.text =[NSString stringWithFormat:newFilePath];
NSLog(@"path.text :%@",path.text);
}