Ork*_*ade 29 uiimageview uiimagepickercontroller ios swift
我在用
UIImagePickerControllerDelegate,
UINavigationControllerDelegate,
UIPopoverControllerDelegate
Run Code Online (Sandbox Code Playgroud)
这些代表从我的画廊或我的相机中选择图像.那么,如何在选择图像后获得图像文件大小?
我想用这个:
let filePath = "your path here"
var fileSize : UInt64 = 0
do {
let attr : NSDictionary? = try NSFileManager.defaultManager().attributesOfItemAtPath(filePath)
if let _attr = attr {
fileSize = _attr.fileSize();
print(fileSize)
}
} catch {
}
Run Code Online (Sandbox Code Playgroud)
但是在这里我需要一条路径,但是如果没有路径,我只能通过图像文件获得?
Dha*_*yas 69
guard let aStrUrl = Bundle.main.path(forResource: "1", ofType: "png") else { return }
let aUrl = URL(fileURLWithPath: aStrUrl)
print("Img size = \((Double(aUrl.fileSize) / 1000.00).rounded()) KB")
extension URL {
var attributes: [FileAttributeKey : Any]? {
do {
return try FileManager.default.attributesOfItem(atPath: path)
} catch let error as NSError {
print("FileAttribute error: \(error)")
}
return nil
}
var fileSize: UInt64 {
return attributes?[.size] as? UInt64 ?? UInt64(0)
}
var fileSizeString: String {
return ByteCountFormatter.string(fromByteCount: Int64(fileSize), countStyle: .file)
}
var creationDate: Date? {
return attributes?[.creationDate] as? Date
}
}
Run Code Online (Sandbox Code Playgroud)
Cod*_*JHP 13
extension UIImage {
public enum DataUnits: String {
case byte, kilobyte, megabyte, gigabyte
}
func getSizeIn(_ type: DataUnits)-> String {
guard let data = self.pngData() else {
return ""
}
var size: Double = 0.0
switch type {
case .byte:
size = Double(data.count)
case .kilobyte:
size = Double(data.count) / 1024
case .megabyte:
size = Double(data.count) / 1024 / 1024
case .gigabyte:
size = Double(data.count) / 1024 / 1024 / 1024
}
return String(format: "%.2f", size)
}
}
Run Code Online (Sandbox Code Playgroud)
用法示例: print("Image size \(yourImage.getSizeIn(.megabyte)) mb")
迅捷3/4:
if let imageData = UIImagePNGRepresentation(image) {
let bytes = imageData.count
let kB = Double(bytes) / 1000.0 // Note the difference
let KB = Double(bytes) / 1024.0 // Note the difference
}
Run Code Online (Sandbox Code Playgroud)
请注意kB和KB之间的差异.回答这里,因为在我的情况下,我们有一个问题,而我们认为千字节为1024字节,但服务器端认为它是1000字节,这引起了一个问题.链接了解更多信息.
PS.几乎可以肯定你会使用kB(1000).
| 归档时间: |
|
| 查看次数: |
43200 次 |
| 最近记录: |