简体   繁体   English

从 Swift 中的 UIImage 属性获取图像文件大小以验证图像大小

[英]Get Image File Size from UIImage Property in Swift to validate Image Size

How can I get the File Size from UIImage Property in Swift?如何从 Swift 中的 UIImage 属性获取文件大小?

My intention is to validate Images uploaded by the user.我的目的是验证用户上传的图像。 If it is above certain bytes or Size then I'll remove it otherwise allow the user to upload the file!如果它超过某些字节或大小,那么我将删除它,否则允许用户上传文件!

Thanks in Advance!提前致谢!

You can't get file size from UIImage , can get from the path where uploaded image stored你不能从UIImage获取文件大小,可以从上传图片存储的路径获取

let filePath = "uploaded image url"
var fileSize : UInt64
do {

  let attr = try FileManager.default.attributesOfItem(atPath: (filePath?.path)!)
  fileSize = attr[FileAttributeKey.size] as! UInt64
  print(fileSize)

  let fileSizeWithUnit = ByteCountFormatter.string(fromByteCount: Int64(fileSize), countStyle: .file)
  print("File Size: \(fileSizeWithUnit)")

} catch {
  print("Error: \(error)")
}

Posting this as an answer, since you have a follow-up question.将此作为答案发布,因为您有后续问题。 Since this is a bad UX, and your question is how to compress a UIImage in iOS, the answer is you can use UIImageJPEGRepresentation .由于这是一个糟糕的用户体验,您的问题是如何在 iOS 中压缩UIImage ,答案是您可以使用UIImageJPEGRepresentation and set this param:并设置此参数:

compressionQuality压缩质量

The quality of the resulting JPEG image, expressed as a value from 0.0 to 1.0.生成的 JPEG 图像的质量,表示为 0.0 到 1.0 之间的值。 The value 0.0 represents the maximum compression (or lowest quality) while the value 1.0 represents the least compression (or best quality).值 0.0 表示最大压缩(或最低质量),而值 1.0 表示最小压缩(或最佳质量)。

You could maybe have a cropping feature in your app.您的应用程序中可能有裁剪功能。

Doc: https://developer.apple.com/documentation/uikit/1624115-uiimagejpegrepresentation文档: https : //developer.apple.com/documentation/uikit/1624115-uiimagejpegrepresentation

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM