Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating size (in bytes) of an image in memory

Tags:

ios

swift

uiimage

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?

like image 666
Vik Avatar asked Jan 10 '23 04:01

Vik


2 Answers

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) 
like image 188
Mick MacCallum Avatar answered Jan 19 '23 14:01

Mick MacCallum


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).

like image 24
qwerty_so Avatar answered Jan 19 '23 15:01

qwerty_so