uiimagepickercontroller - get the name of the image selected from photo library

前端 未结 2 783
星月不相逢
星月不相逢 2021-02-03 14:25

I am trying to upload the image from my iPhone/iPod touch to my online repository, I have successfully picked the image from Photo Album but i am facing one problem i want to kn

2条回答
  •  半阙折子戏
    2021-02-03 15:22

    Instead of using the usual image picker method (UIImage*)[info valueForKey:UIImagePickerOriginalImage] which gives you the selected image as an instance of UIImage, you can use the AssetsLibrary.framework and export the actual source file (including format, name and all metadata). This also has the advantage of the original file format (png or jpg) being preserved.

    #import 
    
    - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
        [self dismissPicker];
        // try to get media resource (in case of a video)
        NSURL *resourceURL = [info objectForKey:UIImagePickerControllerMediaURL];
        if(resourceURL) {
            // it's a video: handle import
            [self doSomethingWith:resourceURL];
        } else {
            // it's a photo
            resourceURL = [info objectForKey:UIImagePickerControllerReferenceURL];
    
            ALAssetsLibrary *assetLibrary = [ALAssetsLibrary new];
            [assetLibrary assetForURL:resourceURL
                          resultBlock:^(ALAsset *asset) {
                              // get data
                              ALAssetRepresentation *assetRep = [asset defaultRepresentation];
                              CGImageRef cgImg = [assetRep fullResolutionImage];
                              NSString *filename = [assetRep filename];
                              UIImage *img = [UIImage imageWithCGImage:cgImg];
                              NSData *data = UIImagePNGRepresentation(img);
                              NSString *cacheDir = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
                              NSURL *tempFileURL = [NSURL fileURLWithPath:[cacheDir stringByAppendingPathComponent:filename]];
                              BOOL result = [data writeToFile:tempFileURL.path atomically:YES];
                              if(result) {
                                  // handle import
                                  [self doSomethingWith:resourceURL];
                                  // remove temp file
                                  result = [[NSFileManager defaultManager] removeItemAtURL:tempFileURL error:nil];
                                  if(!result) { NSLog(@"Error removing temp file %@", tempFileURL); }
                              }
                          }
                         failureBlock:^(NSError *error) {
                             NSLog(@"%@", error);
                         }];
            return;
        }
    }
    

提交回复
热议问题