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

发布于 2024-10-08 01:20:21 字数 684 浏览 0 评论 0原文

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

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

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

我在网上进行了搜索,但大多数示例都在回调处停止,并显示一条很好的消息,表明图像已成功保存。 我只是想知道它保存在哪里。

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

I'm saving a merged image to the iPhone photo library using:

UIImageWriteToSavedPhotosAlbum(viewImage, self, @selector(savedPhotoImage:didFinishSavingWithError:contextInfo:), nil);

And getting the callback using:

- (void) savedPhotoImage:(UIImage*)image didFinishSavingWithError:(NSError *)error contextInfo: (void *)contextInfo { NSLog(@"%@", [error localizedDescription]);
NSLog(@"info: %@", contextInfo);}

What I would like to get is the path for where the image has been saved, so I can add it to an array which will be used to call up a list of saved items elsewhere in the app.

When I load the image using the picker it displays the path info.
However when I save a created image, I can't find where to pull the saved image path.

I have search about the web, but most examples stop at the callback with a nice message to say the image was saved successfully.
I would just like to be able to know where it was saved.

I understand one method might be to start defining my own paths, but as the method does that for me, I was just hoping it could tell me where it saved to.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

梦巷 2024-10-15 01:20:21

我终于找到了答案。
显然 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];

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

I finally found out the answer.
Apparently the UIImage methods strip out metadata and so using UIImageWriteToSavedPhotosAlbum is no good.

However in ios4 Apple put in a new framework to handle the photo library called the ALAssetsLibrary.

First you need to right click on the Targets and in the build part, add the AlAsset Framework to your project with the little + icon in the bottom left.

Then add #import "AssetsLibrary/AssetsLibrary.h"; to the header file of your class.

Finally you can use the following code:

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

And that gets the path of the file you just saved.

や三分注定 2024-10-15 01:20:21

我的代码

-(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 import Library 中,并定义 ALAssetsLibraryWriteImageCompletionBlock 的 type def

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

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

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

My code is

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

in .h import Library and define type def of ALAssetsLibraryWriteImageCompletionBlock

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

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

if you don't know how to get <AssetsLibrary/AssetsLibrary.h>, please add existing framework (AssetsLibrary.framework)

怕倦 2024-10-15 01:20:21

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

OlivariesF's answer is missing the key part of this question, retrieve the path:

Here's a code snippet that does everything:

- (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);
                    }
                }];
            }
        }];
    }
春庭雪 2024-10-15 01:20:21

Swift 版本将

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

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

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

Swift Version will be

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

And "import ALAssetsLibrary" in your file.

Project-> Build Phases -> Link binary -> AssetsLibrary.framework

戒ㄋ 2024-10-15 01:20:21
- (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);
}
- (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);
}
三岁铭 2024-10-15 01:20:21

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

ALAssetsLibrary has been deprecated.

This is the way you should do it:

#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);
    }
}];
罗罗贝儿 2024-10-15 01:20:21

Swift 4.1 版本 OlivaresF 的回答

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

                } else {
                }
            }

Swift 4.1 version of OlivaresF's answer

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

                } else {
                }
            }
累赘 2024-10-15 01:20:21

迅捷版

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

Swift version

            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)")
                        
                    }
                    
                }
                
            }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文