簡體   English   中英

將圖像保存到照片庫並獲取保存圖像的URL

[英]Saving image to Photo Library and get the URL of the saved image

我正在嘗試將圖像從相機保存到照片庫,然后存儲保存圖像的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。 有任何想法嗎? 謝謝!

最后,在閱讀了更多內容后,我發現了答案:函數的第一個參數是CGImageRef類型,而(__bridge CGImageRef)沒有達到我的預期; 但是如果我調用UIImage對象的CGImage方法,它就可以了。 正確的方法是:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM