在我的应用程序,用户可以选择从相册或相机在那里我能得到的UIImage表示的照片。 由于这张专辑可能从网络PIC,文件类型,不仅JPG。 然后我需要把它发送到服务器,而不会皈依。 在这里,我只能用NSData的。
我知道UIImageJPEGRepresentation和UIImagePNGRepresentation,但我认为这个两种方法可将原始图像转换。 也许当质量设置为1个UIImageJPEGRepresentation可以得到原来的好看吗?
有没有什么方法来获得原始的UIImage的NSData?
Answer 1:
您可以使用ALAssetsLibrary
和ALAssetRepresentation
得到原始数据。 例:
- (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:
调用失败块。 - 使用此方法,在下一次
assetForURL:
将失败,而无需再次询问用户。 只有当你重置系统设置的位置警告,用户被再次问。
所以,你应该做好准备,这种方法失败,并且使用UIImageJPEGRepresentation
或UIImagePNGRepresentation
作为后备。 但在这种情况下,你不会得到的原始数据,如元数据(EXIF等)的丢失。
Answer 2:
在iOS 8.0+使用PHImageManager.default()。requestImageData()你找到的资产对应的资产后(你可以得到资产PHAsset.fetchAssets()。
查看更多的信息和示例代码我的回答非常类似的问题如何上传从的UIImagePickerController拍摄的图像 。
文章来源: How can i get original nsdata of uiimage?