6

我正在尝试使用以下代码获取我刚刚从相机捕获的图像的名称。但[info objectForKey:@"UIImagePickerControllerReferenceURL"]总是返回零。我怎样才能得到网址?

- (void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info {
    self.myinfo = info;
    NSLog(@"Dismissing camera ui...");
    [self.cameraUI dismissViewControllerAnimated:YES completion:nil];

    NSLog(@"Getting media url...");
    NSString *mediaURL = [info objectForKey:UIImagePickerControllerMediaURL];
    NSLog(@"Media url = %@", mediaURL);

    NSLog(@"Getting media type...");
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    NSLog(@"Selected mediaType: %@", mediaType);

    if(mediaURL) {
        NSLog(@"This is a video = %@", mediaURL);

        if (![mediaType isEqualToString:(NSString*)kUTTypeVideo]) {
            UISaveVideoAtPathToSavedPhotosAlbum(mediaURL, self, @selector(video:didFinishSavingWithError:contextInfo:), NULL);
        }
    } else {
        NSLog(@"This is a photo...");
        self.originalImage = (UIImage *) [info objectForKey:UIImagePickerControllerOriginalImage];

        if (self.source == UIImagePickerControllerSourceTypeCamera && [mediaType isEqualToString:(NSString*)kUTTypeImage]) {
            // Image captured from camera
            NSLog(@"Saving new image...");

            if (self.source != UIImagePickerControllerSourceTypePhotoLibrary) {
                UIImageWriteToSavedPhotosAlbum(self.originalImage, self,
                    @selector(image:didFinishSavingWithError:usingContextInfo:), nil);
            }
        }
        // Image selected from previous images.
        else {
            NSLog(@"Getting reference url...");
            self.referenceURL = [info objectForKey:@"UIImagePickerControllerReferenceURL"];
            NSLog(@"Reference url = %@", [self.referenceURL absoluteString]);

            [self saveAssetData:self.originalImage :info];
        }
    }
}

- (void)image:(UIImage *)image
didFinishSavingWithError:(NSError *)error
 usingContextInfo:(void*)ctxInfo {

    if (error) {
        NSLog(@"Resim kaydedilemedi: %@", [error localizedDescription]);
        NSString *title = @"Resim kaydedilemedi!";
        NSString* message = @"Resim kaydedilirken hata oluştu!";
        [self alertStatus:message:title];
    } else {
        NSLog(@"Save asset data...");
        [self saveAssetData:image :self.myinfo];
    }
}

- (void)saveAssetData:(UIImage*)originalImage :(NSDictionary*)info {
    self.assetLibrary = [[ALAssetsLibrary alloc] init];
    NSURL *url = [info objectForKey:@"UIImagePickerControllerReferenceURL"];

    ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *asset)
    {
        ALAssetRepresentation *assetRep = [asset defaultRepresentation];

        NSString *filename = [assetRep filename];
        NSLog(@"File name = %@", filename);

        if(self.selectedMediaNames == nil)
            self.selectedMediaNames = [[NSMutableArray alloc] init];

        [self.selectedMediaNames addObject:filename];
        [self.tableView reloadData];
        [self.activitIndicator stopAnimating];
        [self.activitIndicator setHidden:true];

        HMXSharedDataManager *sharedDataManager =
        [HMXSharedDataManager sharedManager];

        [sharedDataManager.uploaMedias addObject:originalImage];
        [sharedDataManager.uploaMediaNames addObject:filename];
    };

    ALAssetsLibraryAccessFailureBlock failureblock  = ^(NSError *error)
    {
        NSLog(@"%@", error);
    };

    [self.assetLibrary assetForURL:url resultBlock:resultblock failureBlock:failureblock];
}

更新:

有点晚了,但在这里我如何获得图像或视频的名称:

  • 检查UIImagePickerControllerMediaURL,如果是null媒体是图像如果不是它是视频
  • 如果图像或视频是刚刚拍摄或录制的,请将其保存到相册
  • 用于ALAssetsLibrary查询文件名。

这是保存和获取媒体的代码:

- (void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info {
    @try {
        [self.cameraUI dismissViewControllerAnimated:YES completion:nil];
        mediaURL = [info objectForKey:UIImagePickerControllerMediaURL];

        // If mediaURL is not null this should be a video
        if(mediaURL) {

            // This video is new just recorded with camera
            if (self.source == UIImagePickerControllerSourceTypeCamera) {
                // First save the video to photos album
                ALAssetsLibrary *library = [ALAssetsLibrary new];
                [library writeVideoAtPathToSavedPhotosAlbum:mediaURL completionBlock:^(NSURL *assetURL, NSError *error){
                    if (error) {
                        DDLogDebug(@"Failed to save the photo to photos album...");
                    } else {
                        // Get the name of the video
                        [self getMediaName:nil url:assetURL];
                    }
                }];
            } else { // This is a video that recorded before
                // Get the name of the video
                [self getMediaName:nil url:[info objectForKey:UIImagePickerControllerReferenceURL]];
            }
        }
        // This is an image
        else {
            self.originalImage = (UIImage*)[info objectForKey:UIImagePickerControllerOriginalImage];

            // This image is new just taken with camera
            if (self.source == UIImagePickerControllerSourceTypeCamera) {
                // First save the image to photos album
                ALAssetsLibrary *library = [ALAssetsLibrary new];
                [library writeImageToSavedPhotosAlbum:[self.originalImage CGImage]
                                          orientation:(ALAssetOrientation)[self.originalImage imageOrientation]
                                      completionBlock:^(NSURL *assetURL, NSError *error){
                    if (error) {
                        DDLogDebug(@"Failed to save the vide to photos album...");
                    } else {
                        // Get the name of the image
                        [self getMediaName:self.originalImage url:assetURL];
                    }
                }];
            } else { // This is an image that taken before
                // Get the name of the image
                [self getMediaName:self.originalImage
                                url:[info objectForKey:@"UIImagePickerControllerReferenceURL"]];
            }
        }
    }
    @catch (NSException *exception) {
        DDLogError(@"%@", [exception description]);
    }
}

获取媒体名称的实际方法:

- (void)getMediaName:(UIImage*)originalImage url:(NSURL*)url {
    @try {
        ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *asset) {
            if (asset == nil) return;
            ALAssetRepresentation *assetRep = [asset defaultRepresentation];
            NSString *fileName = [assetRep filename];
            // Do what you need with the file name here
        };

        ALAssetsLibraryAccessFailureBlock failureblock  = ^(NSError *error) {
            DDLogError(@"Failed to get image or video name : %@", error);
        };

        ALAssetsLibrary *library = [ALAssetsLibrary new];
        [library assetForURL:url resultBlock:resultblock failureBlock:failureblock];
    }
    @catch (NSException *exception) {
        DDLogError(@"%@", [exception description]);
    }
}
4

3 回答 3

5

您使用相机从应用程序中捕获的图像没有名称。它始终为零。您必须以编程方式将该图像保存在照片库中,并且可以使用您想要的任何名称进行保存。

于 2014-04-16T08:25:12.350 回答
1

将以下代码放入 didFinishPickingMediaWithInfo 中:

NSURL *mediaUrl;
NSString *imageURLString;

 self.selectImage = [info valueForKey:UIImagePickerControllerEditedImage];

if (mediaUrl == nil) {

    if (self.selectImage == nil) {

        self.selectImage =  [info valueForKey:UIImagePickerControllerOriginalImage];
        DebugLog(@"Original image picked.");

    }else {

        DebugLog(@"Edited image picked.");

    }

}

mediaUrl = (NSURL *)[info valueForKey:UIImagePickerControllerMediaURL];
imageURLString=[mediaUrl absoluteString];

DebugLog(@"Hi Image URL STRING : - %@",imageURLString);

if ([StringUtils string:imageURLString contains:@"PNG"] || [StringUtils string:imageURLString contains:@"png"]) {


    self.isJPG = NO;
    self.profileImageName = @"profileImageName.png";

} else if ([StringUtils string:imageURLString contains:@"JPG"] || [StringUtils string:imageURLString contains:@"jpg"]) {


    self.isJPG = YES;
    self.profileImageName = @"profileImageName.jpg";

}

当你为 kUTTypeMovie 设置摄像头时,只有你会得到 referenceurl 和 mediaurl。它将为 kUTTypeImage 返回 null。

于 2014-04-16T08:26:19.807 回答
1

对于 Xamarin.iOS 开发人员:存储从相机捕获的图像并使用 ALAssetsLibrary 获取其数据

var originalImage = e.Info[UIImagePickerController.OriginalImage] as UIImage;
var meta = e.Info[UIImagePickerController.MediaMetadata] as NSDictionary;

//Get image bytes 
if (originalImage != null) 
{
    using (NSData imageData = originalImage.AsPNG())
    {
        myByteArray = new Byte[imageData.Length];
        System.Runtime.InteropServices.Marshal.Copy(imageData.Bytes, myByteArray, 0, Convert.ToInt32(imageData.Length));
    }

    //This bit of code saves image to the Photo Album with metadata
    ALAssetsLibrary library = new ALAssetsLibrary();
    library.WriteImageToSavedPhotosAlbum(originalImage.CGImage, meta, (assetUrl, error) =>
    {
        library.AssetForUrl(assetUrl, delegate (ALAsset asset)
        {
            ALAssetRepresentation representation = asset.DefaultRepresentation;
            if (representation != null)
            {
                string fileName = representation.Filename;
                var filePath = assetUrl.ToString();
                var extension = filePath.Split('.')[1].ToLower();
                var mimeData = string.Format("image/{0}", extension);
                var mimeType = mimeData.Split('?')[0].ToLower();
                var documentName = assetUrl.Path.ToString().Split('/')[1];
            }
        }, delegate (NSError err) {
            Console.WriteLine("User denied access to photo Library... {0}", err);
        });
    });
}
于 2019-07-06T11:20:29.460 回答