5

Suppose there is a PHAsset representing image. How to get file size of the image?

The only way I see is using valueForKey: with private ALAssetURL key, and retrieving size of ALAssetRepresentation, but apple can reject such app.

kelin
  • 11,323
  • 6
  • 67
  • 104

2 Answers2

13

Swift 4/5 solution

Extension

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

Function

func getImageFileSize(from asset: PHAsset) -> Float{
    let resource = PHAssetResource.assetResources(for: asset)
    let imageSizeByte = resource.first?.value(forKey: "fileSize") as! Float
    let imageSizeMB = imageSizeByte / (1024.0*1024.0)
    return imageSizeMB
}
Mamad Farrahi
  • 394
  • 1
  • 5
  • 20
  • 1
    Note that if you have modify your photo or video in Photos app, you will get multiple resources, include original media and modified media, and the adjustment data. So you should judge the type of `PHAssetResource`, but not to use the first one. – Franz Wang Jun 04 '20 at 05:10
  • 1
    Slow-motion videos have multiple resources too. – Franz Wang Jun 04 '20 at 05:14
0

You can create an ALAsset from a PHAsset without using any private functions as described here: How to get an ALAsset URL from a PHAsset?

However getting file sizes is problematic in the context of iCloud Photo Library. For photos not on the device you might get a value of "0" or the size of the version on the device, which is not the original in very case.

Community
  • 1
  • 1
holtmann
  • 6,043
  • 32
  • 44
  • You asked for a non private solution. The solution stated in the link above uses only public APIs. – holtmann Nov 24 '15 at 13:25
  • The API is public, but the way you build an asset URL relies on the undocumented assumption. That's why I didn't accept this answer yet. – kelin Jun 20 '17 at 22:17