我怎样才能获得uiimage的原始nsdata?

xi.*_*lin 1 uiimage nsdata ios

在我的应用程序中,用户可以从相册或相机中选择一张照片,在那里我可以获得uiimage表示.由于专辑可能有来自网络的图片,因此文件类型不仅仅是jpg.然后我需要将它发送到服务器而不转换.在这里我只能使用nsdata.
我知道UIImageJPEGRepresentation和UIImagePNGRepresentation,但我认为这两种方法可能会转换原始图像.也许当质量设置为1 UIImageJPEGRepresentation可以获得原始图片?
有没有什么方法可以获得原始的uiimage nsdata?

Mar*_*n R 7

您可以使用ALAssetsLibraryALAssetRepresentation来获取原始数据.例:

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSURL *imageURL = [info objectForKey:UIImagePickerControllerReferenceURL];
    ALAssetsLibrary* library = [[ALAssetsLibrary alloc] init];
    [library assetForURL:imageURL resultBlock:^(ALAsset *asset) {
        ALAssetRepresentation *repr = [asset defaultRepresentation];
        NSUInteger size = repr.size;
        NSMutableData *data = [NSMutableData dataWithLength:size];
        NSError *error;
        [repr getBytes:data.mutableBytes fromOffset:0 length:size error:&error];
            /* Now data contains the image data, if no error occurred */
    } failureBlock:^(NSError *error) {
        /* handle error */
    }];
}
Run Code Online (Sandbox Code Playgroud)

但有一些事情需要考虑:

  • assetForURL: 异步工作.
  • 在设备上,使用assetForURL:会导致确认对话框,这可能会刺激用户:

"您的应用"想要使用您当前的位置.这允许访问照片和视频中的位置信息.

  • 如果用户拒绝访问,则assetForURL:调用失败块.
  • 下次使用此方法时,assetForURL:如果不再询问用户,将会失败.只有在"系统设置"中重置位置警告时,才会再次询问用户.

因此,您应该准备好此方法失败并使用UIImageJPEGRepresentationUIImagePNGRepresentation作为后备.但在这种情况下,您将无法获得原始数据,例如缺少元数据(EXIF等).