How to obtain the original file name of the image

2020-04-16 17:10发布

问题:

I've implemented the delegate method and can get access to the picked UIImage, like this:

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    UIImage *pickedImage = [info valueForKey:UIImagePickerControllerOriginalImage];

I want to save it to a directory, but I need a file name. So rather than just picking a random file name it would make sense to pick the same file name as the image.

Is there a way to retrieve it from that info dictionary?

回答1:

You could use the UIImagePickerControllerReferenceURL value of the info dictionary instead of the UIImagePickerControllerOriginalImage. This should give you the URL to the original media item.

This would return you a NSURL object which you then can use to build your new filename from.



回答2:

  • Use ALA Assets library framework
  • Use the code below

    
        ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
        UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
        [library writeImageToSavedPhotosAlbum:image.CGImage orientation:(ALAssetOrientation)image.imageOrientation completionBlock:^(NSURL *assetURL, NSError *error )
        {
           [library assetForURL:assetURL resultBlock:^(ALAsset *asset )
           {
             ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *imageAsset)
             {
                 ALAssetRepresentation *imageRep = [imageAsset defaultRepresentation];
                 NSLog(@"reference image filename picking from camera: %@", [imageRep filename]);
             };
             ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc] init];
             [assetslibrary assetForURL:assetURL resultBlock:resultblock failureBlock:nil];
           }
           failureBlock:^(NSError *error )
           {
               NSLog(@"Error loading asset");
           }];
        }];
    
    
    imageView.image = [info objectForKey:UIImagePickerControllerEditedImage];
    imageView.contentMode = UIViewContentModeScaleAspectFit;