Calculating the size (in bytes) of an image in memory

I am writing a small application in Swift to resize an image. I would like to calculate the size of the modified image (in bytes / kilobytes). How should I do it?

Here is the code snippet I'm 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 has not yet been saved, how can I calculate its size?

+4
source share
2 answers

Since you want to display the file size for your user, NSByteCountFormatter is a good solution. It accepts NSData and can output a string representing the size of the data in a human-like format (e.g. 1 KB, 2 MB, etc.).

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) 
+8

:

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

imageBuffer (. ).

+1

Source: https://habr.com/ru/post/1569826/


All Articles