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.
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
}
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.