I am writing a small app in Swift to resize an image. I would like to calculate the size of the resized image (in bytes/KB). How do I do that?
Here is the piece of code I am working on:
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
Since scaledImage is not yet saved, how do I go about calculating its size?
Since you're looking to display the size of the file to your user, NSByteCountFormatter is a good solution. It takes NSData, and can output a String representing the size of the data in a human readable format (like 1 KB, 2 MB, etc).
Since you're dealing with a UIImage though, you'll have to convert the UIImage to NSData to use this, which for example, can be done using UIImagePNGRepresentation()
or UIImageJPEGRepresentation()
, which returns NSData representative of the image in the specified format. A usage example could look something like this:
let data = UIImagePNGRepresentation(scaledImage)
let formatted = NSByteCountFormatter.stringFromByteCount(
Int64(data.length),
countStyle: NSByteCountFormatterCountStyle.File
)
println(formatted)
Edit: If as suggested by your title, you're looking to show this information with a specific unit of measurement (bytes), this can also be achieved with NSByteCountFormatter. You just have to create an instance of the class and set its allowedUnits
property.
let data = UIImagePNGRepresentation(scaledImage)
let formatter = NSByteCountFormatter()
formatter.allowedUnits = NSByteCountFormatterUnits.UseBytes
formatter.countStyle = NSByteCountFormatterCountStyle.File
let formatted = formatter.stringFromByteCount(Int64(data.length))
println(formatted)
I used this to create my image:
var imageBuffer: UnsafeMutablePointer<UInt8> = nil
let ctx = CGBitmapContextCreate(imageBuffer, UInt(width), UInt(height), UInt(8), bitmapBytesPerRow, colorSpace, bitmapInfo)
imageBuffer is allocated automatically (see according documentation).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With