How can I get the original nsdata from uiimage?

In my application, the user can select pic from an album or camera, where I can get a uiimage view. Since an album can have a pic from the Internet, the file type is not just jpg. Then I need to send it to the server without conversion. Here I can only use nsdata.
I know the UIImageJPEGRepresentation and the UIImagePNGRview, but I think these two methods can transform the original image. Maybe when the quality set to 1 UIImageJPEGRepresentation can get the original image?
Is there a way to get the original uiimage nsdata?

+1
source share
2 answers

You can use ALAssetsLibrary and ALAssetRepresentation to get the source 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 result in a confirmation dialog, which can annoy the user:

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

  • If the user denies access, assetForURL: causes a block of failures.
  • The next time you use this method, assetForURL: will fail without asking the user again. Only if you specified reset location alerts in the system settings will the user again ask.

So, you should be prepared for the failure of this method and use UIImageJPEGRepresentation or UIImagePNGRepresentation as a backup. But in this case, you will not get the source data, for example. metadata (EXIF, etc.) are missing.

+6
source

On iOS 8.0+, use PHImageManager.default (). requestImageData () after you find the corresponding asset in the assets (you can get the assets using PHAsset.fetchAssets ().

More details and sample code in my answer to a very similar question How to load an image that was taken from UIImagePickerController .

0
source

All Articles