将图像保存到照片库并获取保存图像的URL

时间:2014-01-29 20:23:44

标签: ios objective-c alassetslibrary

我正在尝试将图像从相机保存到照片库,然后存储已保存图像的URL。我的代码:

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {

ALAssetsLibrary *library = [[ALAssetsLibrary alloc]init];
[library writeImageToSavedPhotosAlbum:(__bridge CGImageRef)([info objectForKey:UIImagePickerControllerOriginalImage])
                          orientation:ALAssetOrientationUp completionBlock:^(NSURL *assetURL, NSError *error) {
                              if(error == nil) {
                                  _myImageUrl = [NSString stringWithFormat:@"%@",assetURL];
                                  NSLog(@"%@",assetURL);
                              } else NSLog(@"%@",error);
                          }];

[picker dismissViewControllerAnimated:YES completion:nil];}

我的问题是assetUrl总是为NULL。有任何想法吗? 谢谢!

1 个答案:

答案 0 :(得分:1)

最后,在阅读了更多内容之后,我找到了答案:函数的第一个参数是CGImageRef类型,而(__bridge CGImageRef)不符合我的预期;但如果我调用CGImage对象的UIImage方法,它就可以了。正确的方法是:

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {

    ALAssetsLibrary *library = [[ALAssetsLibrary alloc]init];
    CGImageRef image = [[info objectForKey:UIImagePickerControllerOriginalImage] CGImage];
    [library writeImageToSavedPhotosAlbum:image
                              orientation:ALAssetOrientationUp
                          completionBlock:^(NSURL *assetURL, NSError *error) {
                                  if(error == nil) {
                                      _myImageUrl = [NSString stringWithFormat:@"%@",assetURL];
                                      NSLog(@"%@",assetURL);
                                  } else NSLog(@"%@",error);
                              }];

    self.toDoImage.image = [info objectForKey:UIImagePickerControllerOriginalImage];
    [picker dismissViewControllerAnimated:YES completion:nil];
}