【问题标题】:PhAsset get fileSize iOSPhAsset 获取文件大小 iOS
【发布时间】:2023-03-31 02:25:01
【问题描述】:

除了下面的 API 之外,还有什么方法可以从 PHAsset 对象中获取文件大小

 - (PHImageRequestID)requestImageDataForAsset:(PHAsset *)asset options:(nullable PHImageRequestOptions *)options resultHandler:(void(^)(NSData *__nullable imageData, NSString *__nullable dataUTI, UIImageOrientation orientation, NSDictionary *__nullable info))resultHandler;

我们可以在 ALAsset 对象中直接获取文件大小,但我在 PHAsset 对象中找不到它。

提前致谢。

【问题讨论】:

    标签: ios objective-c photolibrary


    【解决方案1】:

    斯威夫特 5

    PHAsset 获取file size(MB):

    extension PHAsset {
        var fileSize: Float {
            get {
                let resource = PHAssetResource.assetResources(for: self)
                let imageSizeByte = resource.first?.value(forKey: "fileSize") as? Float ?? 0
                let imageSizeMB = imageSizeByte / (1024 * 1024)
                return imageSizeMB
            }
        }
    }
    

    【讨论】:

      【解决方案2】:

      很遗憾,PHAsset 不包含此类信息。另请注意,如果图像在云中,ALAsset 的 fileSize 将无法正常工作。 因此,如果您需要一种稳定的方式从云和本地存储中获取图像大小,只需使用以下方法:

      // Fetch image data to retrieve file size and path
      PHImageRequestOptions * options = [[PHImageRequestOptions alloc] init];
      options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
      options.resizeMode = PHImageRequestOptionsResizeModeExact;
      
      options.synchronous = YES; //Set this to NO if is needed
      
      [[PHImageManager defaultManager] requestImageDataForAsset:photoAsset
                                                        options:options
                                                  resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, UIImageOrientation orientation, NSDictionary * _Nullable info)
       {
           //(CGFloat)imageData.length returns size in bytes
           NSLog(@"%@",[NSString stringWithFormat:@"%.2lf MB", ((CGFloat)imageData.length)/1024/1024]);
       }];
      

      为了获得一点性能集options.sunchronous = NO;
      但是,如果您需要更高的性能,您可以 tryPHAsset 创建一个 ALAsset 对象并从那里获取 fileSize,但请记住,不推荐使用 ALAssetLibrary 并且从云获取图像的文件大小将无法正常工作。

      【讨论】:

      • 我知道 requestImageDataForAsset 但它非常耗时。除了这个API还有什么办法
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-02
      • 1970-01-01
      • 2017-12-20
      • 2015-12-17
      • 1970-01-01
      • 1970-01-01
      • 2016-03-21
      相关资源
      最近更新 更多