51

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

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

当我使用选择器加载图像时,它会显示路径信息。但是,当我保存创建的图像时,我找不到在哪里提取保存的图像路径。

我在网上搜索过,但大多数示例都在回调中停止,并带有一条很好的消息,说明图像已成功保存。我只想知道它保存在哪里。

我知道一种方法可能是开始定义我自己的路径,但是当该方法为我这样做时,我只是希望它可以告诉我它保存到哪里。

4

8 回答 8

86

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

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

首先,您需要右键单击目标,然后在构建部分中,使用左下角的小 + 图标将 AlAsset 框架添加到您的项目中。

然后添加#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];

这将获取您刚刚保存的文件的路径。

于 2010-12-16T07:42:28.287 回答
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)

于 2011-03-18T19:31:43.093 回答
3

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);
                    }
                }];
            }
        }];
    }
于 2018-12-05T07:14:37.547 回答
1

斯威夫特版本将是

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

并在您的文件中“导入 ALAssetsLibrary”。

项目-> 构建阶段-> 链接二进制文件-> AssetsLibrary.framework

于 2016-02-27T15:13:14.960 回答
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);
}
于 2010-12-16T07:55:18.533 回答
0

Swift 4.1 版本的 OlivaresF 的回答

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

                } else {
                }
            }
于 2018-07-05T15:34:36.750 回答
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)")
                        
                    }
                    
                }
                
            }
于 2020-07-02T20:46:24.780 回答
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);
    }
}];
于 2018-03-09T02:40:38.047 回答