iPhone:如何获取使用UIImageWriteToSavedPhotosAlbum()保存的图像的文件路径?

时间:2010-12-16 06:04:07

标签: iphone ios uiimage save photolibrary

我正在使用以下方法将合并后的图片保存到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);}

我想得到的是图像保存位置的路径,因此我可以将其添加到一个数组中,该数组将用于调用应用程序中其他位置的已保存项目列表。

当我使用选择器加载图像时,它会显示路径信息。 但是,当我保存创建的图像时,我无法找到保存图像路径的位置。

我有关于网络的搜索,但是大多数示例都停留在回调上,并提供了一条很好的消息,表示图像已成功保存。 我希望能够知道它的保存位置。

我理解一种方法可能是开始定义我自己的路径,但正如方法为我做的那样,我只是希望它可以告诉我它保存在哪里。

8 个答案:

答案 0 :(得分:85)

我终于找到了答案。 显然UIImage方法剥离了元数据,因此使用UIImageWriteToSavedPhotosAlbum并不好。

然而,在ios4中,Apple推出了一个新框架来处理名为ALAssetsLibrary的照片库。

首先,您需要右键单击目标,然后在构建部分中,使用左下角的小+图标将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];

这就是你刚刚保存的文件的路径。

答案 1 :(得分:3)

我的代码是

-(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导入库中并定义ALAssetsLibraryWriteImageCompletionBlock的类型def

#import <UIKit/UIKit.h>
#import <AssetsLibrary/AssetsLibrary.h>

typedef void (^ALAssetsLibraryWriteImageCompletionBlock)(NSURL *assetURL, NSError *error);

如果您不知道如何获取<AssetsLibrary/AssetsLibrary.h>,请添加现有框架(AssetsLibrary.framework)

答案 2 :(得分:2)

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);
                    }
                }];
            }
        }];
    }

答案 3 :(得分:1)

Swift版本将

 ALAssetsLibrary().writeImageToSavedPhotosAlbum(editedImage.CGImage, orientation: ALAssetOrientation(rawValue: editedImage.imageOrientation.rawValue)!,
                completionBlock:{ (path:NSURL!, error:NSError!) -> Void in
                    print("\(path)")
            })

和&#34;导入ALAssetsLibrary&#34;在你的文件中。

项目 - &GT;构建阶段 - &gt;链接二进制 - &gt; AssetsLibrary.framework

答案 4 :(得分:1)

OlivaresF的答案的Swift 4.1版本

        PHPhotoLibrary.shared().performChanges({
                PHAssetChangeRequest.creationRequestForAsset(from: image)
            }) { (success, error) in
                if success {

                } else {
                }
            }

答案 5 :(得分:0)

- (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);
}

答案 6 :(得分:0)

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);
    }
}];

答案 7 :(得分:0)

快速版本

            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)")
                        
                    }
                    
                }
                
            }