使用UIImagePickerControllerReferenceURL在UIImageView上设置Image

时间:2011-12-01 15:10:22

标签: iphone uiimageview

是否可以使用UIImageView设置图像    UIImagePickerControllerReferenceURL。传统模式正在使用 [info objectForKey:@“UIImagePickerControllerOriginalImage”];

I tried this:

theImageView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[info objectForKey:UIImagePickerControllerReferenceURL]]];

但是在UIImageView上没有设置图像。

请帮助。

2 个答案:

答案 0 :(得分:5)

NSURL *referenceURL = [info objectForKey:UIImagePickerControllerReferenceURL];
        ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
        [library assetForURL:referenceURL resultBlock:^(ALAsset *asset)
         {
           UIImage  *copyOfOriginalImage = [UIImage imageWithCGImage:[[asset defaultRepresentation] fullResolutionImage]];
             theImageView.image = copyOfOriginalImage;
         }
                failureBlock:^(NSError *error)
         {
             // error handling
         }];
        [library release];

这段代码就行了。 :)

答案 1 :(得分:1)

您需要在代码中执行更多错误处理,而不是在一行中嵌入四个或五个函数。

请考虑一下:

NSURL * referenceURL = [info objectForKey: UIImagePickerControllerReferenceURL];
if(referenceURL == NULL)
{
    NSLog( @"reference URL is null");
} else {
    NSData * imageData = [NSData dataWithContentsOfURL: referenceURL];
    if(imageData == NULL)
    {
        NSLog( @"no image data found for URL %@", [referenceURL absoluteString] );
    } else {
        UIImage * theActualImage = [UIImage imageWithData: imageData];
        if(theActualImage == NULL)
        {
            NSLog( @"the data at URL %@ is not an image", [referenceURL absoluteString] );
        } else {
            if(theImageView == NULL)
            {
                NSLog( @"I forgot to set theImageView" );
            } else {
                theImageView.image = theActualImage;
            }
        }
    }
}

我希望此信息可以帮助您。