请查看谷歌搜索“1KB等于多少字节”,答案为1000。
https://www.google.com/search?q=1+kb+%3D+how+many+bytes&oq=1+kb+%3D+how+many+bytes&aqs=chrome..69i57.8999j0j1&sourceid=chrome&ie=UTF-8
在获取适当的大小时,我通过将图像添加到应用程序包和模拟器中的照片中添加了多个方案。
我从我的 Mac 上取出的图像大小为299.0 KB。
场景1:将图像添加到应用程序包中
在 Xcode 中添加图像后,它在项目目录中的大小将保持不变。但是,如果您从其路径获取它,则其大小将缩小到257.0 KB。这是设备或模拟器中使用的图像的实际大小。
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
}
}
方案2: 在模拟器中向照片添加图像
将图像添加到模拟器或设备的照片中,图像的大小从299.0 KB增加到393.0 KB。这是存储在设备或模拟器文档目录中的图像的实际大小。
Swift 4及更早版本
var image = info[UIImagePickerControllerOriginalImage] as! UIImage
var imgData: NSData = NSData(data: UIImageJPEGRepresentation((image), 1))
var imageSize: Int = imgData.count
print("size of image in KB: %f ", Double(imageSize) / 1000.0)
Swift 5
let image = info[UIImagePickerController.InfoKey.originalImage] as! UIImage
let imgData = NSData(data: image.jpegData(compressionQuality: 1)!)
var imageSize: Int = imgData.count
print("actual size of image in KB: %f ", Double(imageSize) / 1000.0)
通过添加 .rounded(),它会给你 393.0 KB,不使用它将给出 393.442 KB。因此,请使用上述代码手动检查图像大小一次。由于图像的大小可能因不同的设备和 Mac 而异。我只在 Mac mini 和模拟器 iPhone XS 上进行了检查。