我怎样才能获得uiimage的原始nsdata? [英] How can i get original nsdata of uiimage?
问题描述
在我的应用程序中,用户可以从相册或相机中选择一张可以获得uiimage表示的照片。由于专辑可能有来自网络的图片,因此文件类型不仅仅是jpg。然后我需要将它发送到服务器而不转换。在这里我只能使用nsdata。
我知道UIImageJPEGRepresentation和UIImagePNGRepresentation,但我认为这两种方法可能会转换原始图像。也许当质量设置为1 UIImageJPEGRepresentation可以获得原始图片?
有没有什么方法可以获得原始的uiimage nsdata?
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?
推荐答案
你可以使用 ALAssetsLibrary
和 ALAssetRepresentation
来获取原始数据。示例:
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 */
}];
}
但有些事情需要考虑:
-
assetForURL:
异步工作。 - 在设备上,使用
assetForURL:
将导致确认对话框,这可能会刺激用户:
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.
- 如果用户拒绝访问,
assetForURL:
调用失败块。 - 下次使用此方法时,
assetForURL:
将失败而不再询问用户。只有在系统设置中重置位置警告时,才会再次询问用户。 - 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.
因此,您应该准备好此方法失败并且使用 UIImageJPEGRepresentation
或 UIImagePNGRepresentation
作为后备。但在这种情况下,您将无法获得原始数据,例如缺少元数据(EXIF等)。
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.
这篇关于我怎样才能获得uiimage的原始nsdata?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!