How can i get original nsdata of uiimage?

╄→гoц情女王★ 提交于 2019-11-28 13:01:10

You can use the ALAssetsLibrary and ALAssetRepresentation to get the original data. Example:

- (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 */
    }];
}

But there are some things to consider:

  • assetForURL: works asynchronously.
  • On the device, using assetForURL: will cause a confirmation dialog, which might be irritating the user:

"Your App" would like to use your current location. This allows access to location information in photos and videos.

  • If the user denies access, assetForURL: calls the failure block.
  • The next time you use this method, assetForURL: will fail without asking the user again. Only if you reset the location warnings in System Settings, the user is asked again.

So you should be prepared that this method fails and use UIImageJPEGRepresentation or UIImagePNGRepresentation as a fallback. But in that case you will not get the original data, e.g. the metadata (EXIF etc.) are missing.

Vitalii

On iOS 8.0+ use PHImageManager.default().requestImageData() after you locate the corresponding asset in the assets (you can get to assets with PHAsset.fetchAssets().

See more info and example code in my answer to very similar question How to upload image that was taken from UIImagePickerController.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!