从包含数据的照片库中打开 UIImage



>我有两个视图控制器,其中一个我从照片库中挑选图像并将其分配给图像属性。使用此选取器:

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)img editingInfo:(NSDictionary *)editInfo

但相反,我只想从第一个控制器中的选择器获取图像的地址/数据,推送下一个视图控制器,然后在那里打开具有该地址的图像。因此,我执行以下操作:

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info

当我打印照片的信息时,它看起来像这样:

assets-library://asset/asset.JPG?id=52219875-C221-4F60-B9D4-984AAADB6E63&ext=JPG

问题是UIImage有方法initWithDataimageWithData,但这些方法接受NSData而不是NSDictionary。

如何使用照片库中的数据打开图像?

此方法:

- (void)imagePickerController:(UIImagePickerController *)picker 
        didFinishPickingImage:(UIImage *)img 
                  editingInfo:(NSDictionary *)editInfo

不应该使用,自iOS3以来已被弃用

此方法:

  - (void)imagePickerController:(UIImagePickerController *)picker 
  didFinishPickingMediaWithInfo:(NSDictionary *)info

在报告时返回字典。

图像指针是此字典中的对象之一。您获得它的方式如下:

  UIImage* image = [info objectForKey:UIImagePickerControllerOriginalImage];

这是 Apple 针对该方法的文档。

基本上那本字典里有几个键,听这里:

NSString *const UIImagePickerControllerMediaType;
NSString *const UIImagePickerControllerOriginalImage;
NSString *const UIImagePickerControllerEditedImage;
NSString *const UIImagePickerControllerCropRect;
NSString *const UIImagePickerControllerMediaURL;
NSString *const UIImagePickerControllerReferenceURL;
NSString *const UIImagePickerControllerMediaMetadata;

你可能想要UIImagePickerControllerEditedImage.所以这就是你要找的:

UIImage *theImage = [info valueForKey:UIImagePickerControllerEditedImage];

当然,您也可以使用字典中的其他键从图像中获取其他信息。

字典提供图像的 URL。所以加载数据

NSData *imageData = [NSData dataWithContentsOfURL:[info valueForKey: UIImagePickerControllerReferenceURL]];

并将此数据用于NSImage initWithData方法。

最新更新