【问题标题】:How can i get original nsdata of uiimage?我怎样才能得到uiimage的原始nsdata?
【发布时间】:2012-08-20 17:09:08
【问题描述】:

在我的应用程序中,用户可以从相册或相机中选择一张图片,我可以在其中获取 uiimage 表示。由于相册可能有来自网络的图片,因此文件类型不仅是 jpg。然后我需要将它发送到服务器而不进行转换。这里我只能使用nsdata。
我知道 UIImageJPEGRepresentation 和 UIImagePNGRepresentation,但我认为这两种方法可以转换原始图像。也许当质量设置为 1 UIImageJPEGRepresentation 可以获得原始图片?
有什么方法可以获取原始的uiimage nsdata吗?

【问题讨论】:

  • 据我所知,相机胶卷中的图片以 JPEG 格式存储(至少我在通过 SSH 连接设备并检查文件后看到的是这种格式)。所以 JPEGrepresentation 将适用于您的情况
  • @KaanDedeoglu:许多应用程序都有“存储在相册中”的功能,这也适用于 TIFF、BMP 和其他一些文件类型。

标签: ios uiimage nsdata


【解决方案1】:

在 iOS 8.0+ 上,在资产中找到相应资产后使用 PHImageManager.default().requestImageData()(您可以使用 PHAsset.fetchAssets() 获取资产。

my answer 中查看更多信息和示例代码与非常相似的问题How to upload image that was taken from UIImagePickerController

【讨论】:

    【解决方案2】:

    您可以使用ALAssetsLibraryALAssetRepresentation 来获取原始数据。示例:

    - (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: 将失败,无需再次询问用户。仅当您在系统设置中重置位置警告时,才会再次询问用户。

    所以你应该准备好这个方法失败并使用UIImageJPEGRepresentationUIImagePNGRepresentation 作为后备。但在这种情况下,您将无法获得原始数据,例如元数据(EXIF 等)丢失。

    【讨论】:

    • 谢谢!我还没有注意到 imagePickerController:didFinishPickingImage:editingInfo: 已被弃用。
    猜你喜欢
    • 2014-04-05
    • 1970-01-01
    • 1970-01-01
    • 2018-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-06
    相关资源
    最近更新 更多