我正在Swift中编写一个小应用程序来调整图像大小.我想计算调整大小的图像的大小(以字节/ KB为单位).我怎么做?
这是我正在处理的一段代码:
var assetRepresentation : ALAssetRepresentation = asset.defaultRepresentation()
self.originalImageSize = assetRepresentation.size()
selectedImageSize = self.originalImageSize
// now scale the image
let image = selectedImage
let hasAlpha = false
let scale: CGFloat = 0.0 // Automatically use scale factor of main screen
UIGraphicsBeginImageContextWithOptions(sizeChange, !hasAlpha, scale)
image.drawInRect(CGRect(origin: CGPointZero, size: sizeChange))
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
self.backgroundImage.image = scaledImage
Run Code Online (Sandbox Code Playgroud)
由于scaledImage尚未保存,我该如何计算其大小?
由于您希望向用户显示文件的大小,因此NSByteCountFormatter是一个很好的解决方案.它需要NSData,并且可以以人类可读的格式(如1 KB,2 MB等)输出表示数据大小的String.
由于你正在处理UIImage,你必须将UIImage转换为NSData才能使用它,例如,可以使用UIImagePNGRepresentation()或完成UIImageJPEGRepresentation(),它返回NSData代表指定格式的图像.用法示例可能如下所示:
let data = UIImagePNGRepresentation(scaledImage)
let formatted = NSByteCountFormatter.stringFromByteCount(
Int64(data.length),
countStyle: NSByteCountFormatterCountStyle.File
)
println(formatted)
Run Code Online (Sandbox Code Playgroud)
编辑:如果您的标题建议,您希望以特定的度量单位(字节)显示此信息,这也可以通过NSByteCountFormatter实现.您只需创建类的实例并设置其allowedUnits属性即可.
let data = UIImagePNGRepresentation(scaledImage)
let formatter = NSByteCountFormatter()
formatter.allowedUnits = NSByteCountFormatterUnits.UseBytes
formatter.countStyle = NSByteCountFormatterCountStyle.File
let formatted = formatter.stringFromByteCount(Int64(data.length))
println(formatted)
Run Code Online (Sandbox Code Playgroud)