Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
324 views
in Technique[技术] by (71.8m points)

ios - How can i get original nsdata of uiimage?

In my app, user can select a pic from album or camera where i can get uiimage representation. Since the album may have pic from web, the file type is not only jpg. Then i need to sent it to the server without convertion. Here i can only use nsdata.
I know UIImageJPEGRepresentation and UIImagePNGRepresentation, but i think this two method may convert the original image. Maybe when quality set to 1 UIImageJPEGRepresentation can get original pic?
Is there any method to get the original uiimage nsdata?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...