在内存中计算图像的大小(以字节为单位)

4

我正在使用Swift编写一个小应用程序,用于调整图像大小。 我想计算调整后图像的大小(以字节/千字节为单位)。我该如何做到这一点?

这是我正在处理的代码:

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

由于 scaledImage 尚未保存,我该如何计算它的大小?


3
位图大小?还是在特定格式下它将在磁盘上占用的大小? - Wain
在保存或分享之前,显示图像在磁盘上的大小。(图像尚未保存,我想在保存之前在屏幕上显示其大小。) - Vik
2
使用 UIImageJPEGRepresentationUIImagePNGRepresentation 并获取生成的 NSData 的大小。 - rmaddy
2个回答

8

如果您想向用户显示文件的大小,NSByteCountFormatter 是一个不错的解决方案。它接受 NSData,并可以输出一个字符串表示数据的大小,以人类可读的格式(如 1 KB、2 MB 等)。

但是,由于您处理的是 UIImage,因此您需要将 UIImage 转换为 NSData 才能使用它。例如,可以使用 UIImagePNGRepresentation()UIImageJPEGRepresentation() 进行转换,这些方法返回指定格式中图像的 NSData 表示形式。使用示例可能如下所示:

let data = UIImagePNGRepresentation(scaledImage)
let formatted = NSByteCountFormatter.stringFromByteCount(
    Int64(data.length),
    countStyle: NSByteCountFormatterCountStyle.File
)

println(formatted)

编辑:如果您的标题所示,希望以特定的计量单位(字节)显示此信息,则可以使用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) 

1
我用这个来创建我的图片:

var imageBuffer: UnsafeMutablePointer<UInt8> = nil
let ctx = CGBitmapContextCreate(imageBuffer, UInt(width), UInt(height), UInt(8), bitmapBytesPerRow, colorSpace, bitmapInfo)

imageBuffer会自动分配(请参阅相应文档)。


谢谢您的回复。我正在寻找磁盘上的大小(图像尚未保存,我想在保存之前在屏幕上显示其大小)。 - Vik
我明白了。我不知道如何在上面的例子中获取imageBuffer的大小。但是CGBitmapContextCreate的文档告诉我们缓冲区应该有多大(它是从宽度/高度/颜色映射计算出来的)。 - qwerty_so
我猜你的图像类型是NSImage。如果是这样,你可以使用NSImage.representation.bitsPerSample乘以大小(宽度*高度)。 - qwerty_so

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接